HTML DOM
HTML DOM createAttribute() Method
The createAttribute() method creates a new attribute node with a specified name. You then set its value and attach it to an element with setAttributeNode().
Definition and Usage
document.createAttribute(name) creates and returns an Attr (attribute) node whose name is the given string. The node is not attached to any element until you add it, and its value is empty until you set it.
Syntax
document.createAttribute(name)The name parameter is a string with the attribute name. The method returns an Attr node object.
Example
<button id="btn">A button</button>
<script>
// Create an attribute node
const attr = document.createAttribute("class");
attr.value = "highlight";
// Attach it to the button element
const btn = document.getElementById("btn");
btn.setAttributeNode(attr);
console.log(btn.getAttribute("class")); // "highlight"
</script>createAttribute makes an empty class attribute, attr.value gives it the value "highlight", and setAttributeNode attaches it to the button. The button now has class="highlight", as confirmed by getAttribute.
For most cases element.setAttribute("class", "highlight") is simpler. createAttribute is mainly useful when you need to work with Attr node objects directly.
