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()
:
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: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
: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: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:
const button = document.createElement('button');
const attribute = document.createAttribute('id');
attribute.value = 'some-value';
button.setAttributeNode(attribute);
button.textContent = 'Click me';
document.querySelector('.container').appendChild(button);
By following these steps, you can easily create HTML attributes using vanilla JavaScript.