Latest web development tutorials
 

HTML DOM createAttribute() Method

< Document Object

Example

Create a class attribute, with the value "democlass", and insert it to an <h1> element:

var h1 = document.getElementsByTagName("H1")[0];   // Get the first <h1> element in the document
var att = document.createAttribute("class");       // Create a "class" attribute
att.value = "democlass";                           // Set the value of the class attribute
h1.setAttributeNode(att);                          // Add the class attribute to <h1>

Before creating the attribute:

Hello World

After inserting the attribute:

Hello World

Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The createAttribute() method creates an attribute with the specified name, and returns the attribute as an Attr object.

Tip: Use the attribute.value property to set the value of the attribute.

Tip: Use the element.setAttributeNode() method to add the newly created attribute to an element.

Tip: Often, you will want to use the element.setAttribute() method instead of the createAttribute() method.


Browser Support

Method
createAttribute() Yes Yes Yes Yes Yes

Syntax

document.createAttribute(attributename)

Parameter Values

Parameter Type Description
attributename Attr object Required. The name of the attribute you want to create

Technical Details

Return Value: A Node object, representing the created attribute
DOM Version Core Level 1 Document Object

Examples

More Examples

Example

Create a href attribute, with the value "www.w3ii.com", and insert it to an <a> element:

var anchor = document.getElementById("myAnchor");  // Get the <a> element with id="myAnchor"
var att = document.createAttribute("href");        // Create a "href" attribute
att.value = "http://www.w3ii.com";            // Set the value of the href attribute
anchor.setAttributeNode(att);                      // Add the href attribute to <a>

Before creating the attribute:

After inserting the attribute:

Try it Yourself »

< Document Object