setAttribute()
Last updated
Last updated
setAttribute()
methodTo set a value of an attribute on a specified element, you use the setAttribute()
method:
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.
The setAttribute()
returns .
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 or 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.
setAttribute()
exampleSee the following example:
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.
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
.