Categories
JavaScript Answers

How to add or update an attribute to an HTML element using JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *