setAttribute()
Introduction to the JavaScript setAttribute()
method
setAttribute()
methodTo set a value of an attribute on a specified element, you use the setAttribute()
method:
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
setAttribute()
exampleSee the following example:
How it works:
First, select the button with the id
btnSend
by using thequerySelector()
method.Second, set the value of the
name
attribute tosend
using thesetAttribute()
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
.
Last updated