Cover Image for JavaScript setAttribute() method
108 views

JavaScript setAttribute() method

The setAttribute() method in JavaScript is used to set the value of a specified attribute on an element. It allows you to dynamically add or modify attributes of HTML elements.

The setAttribute() method takes two parameters: the name of the attribute and the value to set. Here’s the syntax:

JavaScript
element.setAttribute(attributeName, attributeValue);
  • attributeName is a string that specifies the name of the attribute you want to set.
  • attributeValue is a string that specifies the value to be assigned to the attribute.

Here’s an example that demonstrates the usage of setAttribute():

HTML<span role="button" tabindex="0" data-code="<button id="myButton">Click me
<button id="myButton">Click me</button>
JavaScript
const button = document.getElementById('myButton');
button.setAttribute('class', 'btn-primary');
button.setAttribute('disabled', 'true');

In this example, the setAttribute() method is used to set the class attribute to 'btn-primary' and the disabled attribute to 'true'. As a result, the button element will have the CSS class btn-primary applied to it, and it will be disabled.

It’s worth noting that if the specified attribute already exists, the setAttribute() method will update its value. If the attribute doesn’t exist, it will be added to the element.

Keep in mind that when working with standard HTML attributes like class, id, or disabled, there are often corresponding properties available that provide a more convenient and readable way to modify their values. However, setAttribute() is particularly useful when dealing with custom attributes or non-standard attributes.

Also, be cautious when modifying attributes that are closely tied to an element’s behavior, such as id or disabled, as changing them dynamically may have unintended consequences on the element’s functionality.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS