JavaScript setAttribute

Summary: in this tutorial, you will learn how to use the JavaScript setAttribute() method to set a value for an attribute on a specified element.

Introduction to the JavaScript setAttribute() method

To set a value of an attribute on a specified element, you use the setAttribute() method:

element.setAttribute(name, value);Code language: CSS (css)

Parameters

The name specifies the attribute name whose value is set. It’s automatically converted to lowercase if you call the setAttribute() on an HTML element.

The value specifies the value to assign to the attribute. It’s automatically converted to a string if you pass a non-string value to the method.

Return value

The setAttribute() returns undefined.

Note that if the attribute already exists on the element, the setAttribute() method updates the value; otherwise, it adds a new attribute with the specified name and value.

Typically, you use the querySelector() or getElementById() to select an element before calling the setAttribute() on the selected element.

To get the current value of an attribute, you use the getAttribute() method. To remove an attribute, you call the removeAttribute() method.

JavaScript setAttribute() example

See the following example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JS setAttribute() Demo</title>
</head>
<body>
    <button id="btnSend">Send</button>

    <script>
        let btnSend = document.querySelector('#btnSend');
        if (btnSend) {
            btnSend.setAttribute('name', 'send');
            btnSend.setAttribute('disabled', '');
        }
    </script>
</body>
</html>
Code language: HTML, XML (xml)

How it works:

  • First, select the button with the id btnSend by using the querySelector() method.
  • Second, set the value of the name attribute to send using the setAttribute() method.
  • Third, set the value of the disabled attribute so that when users click the button, it will do nothing.

Note that the disabled attribute is special because it is a Boolean attribute. If a Boolean attribute is present, whatever value it has, the value is considered to be true. To set the value of a Boolean attribute to false, you need to remove the entire attribute using the removeAttribute() method.

Summary

  • Use the setAttribute() to set the value of an attribute on a specified element.
  • Setting the value of a Boolean attribute to whatever value, that value will be considered to be true.
Was this tutorial helpful ?