setAttribute() in javascript

setAttribute() method in javascript

setAttribute() method is used to set an attribute for an element.

If the specified attribute is already present, the value in it will be updated.

When specifying it both the attribute name and value must be given.

Example

Try Yourself

Example Explanation

  • In the above example following attributes are added, id, onclick and style.
  • When the button is clicked, javascript function is called.
  • In the function, we are getting the particular list item using its id(document.getElementById("id_btn");).
  • Next we are adding the attribute value style and background color as green.
  • Since the attribute is already present, it will be updated and the color will change into green.