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:
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>JS setAttribute() Demo</title></head><body><buttonid="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.