HTML DOM createAttribute() Method
Example
Create a class attribute, with the value "democlass", and insert it to an <h1> element:
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
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
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 |
More Examples
Example
Create a href attribute, with the value "tutorials", and insert it to an <a> element:
var att = document.createAttribute("href"); // Create a "href" attribute
att.value = "http://tutorials"; // 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 »