Sometimes, we want to add or update an attribute to an HTML element using JavaScript.
In this article, we’ll look at how to add or update an attribute to an HTML element using JavaScript.
How to add or update an attribute to an HTML element using JavaScript?
To add or update an attribute to an HTML element using JavaScript, we can set the property in the attributes property.
For instance, we write
const e = document.createElement("div");
e.attributes["id"] = "div1";
to create a div with createElement.
Then we set the id attribute of the div with
e.attributes["id"] = "div1";
Conclusion
To add or update an attribute to an HTML element using JavaScript, we can set the property in the attributes property.