Categories
JavaScript Answers

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

Spread the love

To add/update an attribute to an HTML element using JavaScript, we set 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 its id attribute by setting e.attributes["id"] to 'div1‘.

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 *