Categories
JavaScript Answers

How to Add or Update an Attribute to an HTML Element Using JavaScript?

Spread the love

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.

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 *