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 call the setAttribute method.

For instance, we write

document.getElementById("nav").setAttribute("class", "active");

to select the element with getElementById.

Then we call setAttribute with the attribute name and its value.

Conclusion

To add or update an attribute to an HTML element using JavaScript, we call the setAttribute method.

Leave a Reply

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