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 element’s attribute with JavaScript.

In this article, we’ll look at how to add or update an element’s attribute with JavaScript.

Use the setAttribute Method

One way to add or update an attribute is to use the setAttribute method.

For instance, we can write:

<div>  
  hello world  
</div>

And:

const d = document.querySelector('div');  
d.setAttribute('style', 'color: red')

to set the text color of the div to red.

We call setAttribute with 'style' and 'color: red' to add the style attribute with the value in the 2nd argument.

Use Set the Property of the Element

We can also set the property with the attribute name to add an attribute.

For instance, we can write:

<div>  
  hello world  
</div>

And:

const d = document.querySelector('div');  
d.style = 'color: red'

Then we set the style attribute with the ‘color: red’ string.

Conclusion

One way to add or update an attribute is to use the setAttribute method.

Also, we can also set the property with the attribute name to add an attribute.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.