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 anidattribute:const attribute = document.createAttribute('id'); -
Set its value: Use the
valueproperty 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 theidattribute 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.