JavaScript setAttribute() Method Tutorial

In this section, we will learn what the Element setAttribute() method is and how to use it in JavaScript.

What is Element setAttribute() Method in JavaScript?

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

If the attribute is already set for the target element, then its value will change after calling this method.

Notes:

  • You could use this method to a set value for the style attribute as well. But it is better to use the style property for that purpose because using the setAttribute() method will replace the current value and might lead to the removal of unintentional CSS properties that are already set for the target element.
  • Also, you can use the removeAttribute() method to remove an attribute from an element.

JavaScript setAttribute() Method Syntax:

element.setAttribute(attributeName, value);

JavaScript setAttribute() Method Parameter

The method takes two arguments:

  • The first argument is the name of the attribute we want to set for the target element.
  • The second argument is the value of that attribute.

JavaScript setAttribute() Method Return Value

The method does not return a value.

Example: JavaScript add attribute

See the Pen JavaScript add attribute by Omid Dehghan (@odchan1) on CodePen.

Leave a Reply