JavaScript’s Element.setAttribute()
method sets the value of an attribute of the Element
.
Syntax
Element.setAttribute(name, value);
Parameters
name
A string containing the name of the element’s attribute whose value is to be set.
value
A string containing the value to assign to the attribute.
Return value
The setAttribute()
method does not have a return value, which means that the method implicitly returns undefined
.
Exceptions
InvalidCharacterError
DOMException
Thrown if the specified attribute name contains one or more characters that are not valid in attribute names.
Examples
Here is an example of using the JavaScript setAttribute()
method.
Consider the following line of HTML:
<a href="https://javascriptguide.com" target="_blank">JavaScript Guide</a>
How can we modify the value of the target
attribute with JavaScript?
Well, we can select the a
element with the querySelector()
method and use the setAttribute()
method:
let a = document.querySelector('a');
a.setAttribute('target', '_self');
console.log(a.getAttribute('target'));
The last line logs the current value of the attribute to the console of your browser.
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
setAttribute() |
1 | 12 | 1 | 5 | 8 | 1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 |