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.