How to create an HTML attribute using vanilla Javascript
By Flavio Copes
Learn how to add an attribute to a DOM element with vanilla JavaScript: create it with createAttribute(), set its value, and attach it via setAttributeNode().
To create an HTML attribute with vanilla JavaScript, you create it with document.createAttribute(), set its value, then attach it to the element with setAttributeNode().
Say you have an element, which you selected using querySelector():
const button = document.querySelector('#mybutton')
You can attach an attribute to it following those steps:
- create the attribute
- set its value
- attach the attribute to the element
Example:
const attribute = document.createAttribute('data-product')
attribute.value = 'mountain-bike'
button.setAttributeNode(attribute)
Now the button has a data-product="mountain-bike" attribute, and you can read it back with button.getAttribute('data-product').
createAttribute() gives you an Attr node. It’s a real DOM node, like elements and text nodes, and setAttributeNode() is how you attach it to an element.
What if the element doesn’t exist yet?
If the element does not exist yet, you have to first create it, then create the attribute, then add the attribute to the element, and finally add the element to the DOM:
const button = document.createElement('button')
const attribute = document.createAttribute('data-action')
attribute.value = 'add-to-cart'
button.setAttributeNode(attribute)
button.textContent = 'Add to cart'
document.querySelector('.container').appendChild(button)
The order of the first steps doesn’t matter much. What matters is appending the element to the DOM last, so the browser doesn’t render it half-configured.
The shorter way
In day to day code I reach for setAttribute() instead. It creates the attribute (or updates it, if it already exists) in a single call:
button.setAttribute('data-product', 'mountain-bike')
createAttribute() is worth knowing when you want to work with the attribute as a node, for example when copying attributes from one element to another by iterating element.attributes.
Be careful reusing attribute nodes
An Attr node can belong to one element at a time. If you try to attach the same node to a second element, the browser throws an InUseAttributeError.
The fix: create a fresh attribute for each element. Or clone it first with attribute.cloneNode().
Also notice that calling setAttributeNode() with an attribute name the element already has replaces the old attribute, and the method returns the one it replaced.
Related posts about platform: