How to Create an HTML Attribute Using Vanilla JavaScript
If you need to add an attribute to an HTML element in the DOM using vanilla JavaScript, there are a few steps you can follow. Let’s say you have already selected an element using querySelector()
:
1 | const button = document.querySelector('#mybutton'); |
To attach an attribute to this element, you can follow these steps:
Create the attribute: Use the
document.createAttribute()
method to create the attribute you want to add. For example, to create anid
attribute:1
const attribute = document.createAttribute('id');
Set its value: Use the
value
property to set the value of the attribute. For example, to set the value toremove-item
:1
attribute.value = 'remove-item';
Attach the attribute to the element: Use the
setAttributeNode()
method to attach the attribute to the element. For example, to attach theid
attribute to the selected element:1
button.setAttributeNode(attribute);
If the element does not already exist, you will need to create it, create the attribute, attach the attribute to the element, and then add the element to the DOM.
Here’s an example:
1 | const button = document.createElement('button'); |
By following these steps, you can easily create HTML attributes using vanilla JavaScript.