HTML DOM
HTML DOM createAttribute() Method
The createAttribute() method creates a new attribute node with a given name and returns it. You then set its value and attach it to an element with setAttributeNode().
Definition and Usage
document.createAttribute(name) creates an Attr (attribute) node whose name is the string you pass in. The new attribute has no value yet; you assign one through its value property. Finally you attach it to an element using the element's setAttributeNode() method.
In everyday code, element.setAttribute(name, value) is a shorter way to achieve the same result. createAttribute() is useful when you need a reference to the attribute node itself.
Syntax
document.createAttribute(name)Example
This example creates a class attribute node, gives it a value, and attaches it to a paragraph so the paragraph turns red.
<!DOCTYPE html>
<html>
<head>
<style>.highlight { color: red; font-weight: bold; }</style>
</head>
<body>
<p id="para">This text will be styled.</p>
<button onclick="addAttr()">Add class attribute</button>
<script>
function addAttr() {
const attr = document.createAttribute("class");
attr.value = "highlight";
document.getElementById("para").setAttributeNode(attr);
}
</script>
</body>
</html>More Examples
You can create any attribute this way. Here we build a title attribute so a tooltip appears when you hover over the box.
<!DOCTYPE html>
<html>
<body>
<div id="box" style="padding:20px;background:#eee;">Hover over me</div>
<button onclick="addTitle()">Add a tooltip</button>
<script>
function addTitle() {
const attr = document.createAttribute("title");
attr.value = "I am a tooltip created with createAttribute()";
document.getElementById("box").setAttributeNode(attr);
}
</script>
</body>
</html>For most cases element.setAttribute("class", "highlight") is simpler than creating an attribute node. Reach for createAttribute() only when you specifically need the Attr node object.
Key Takeaways
- createAttribute(name) returns a new, empty attribute node.
- Set its value through the node's value property.
- Attach it with element.setAttributeNode(attr).
- element.setAttribute() is a shorter alternative for most cases.
