Element: getAttribute() method
The getAttribute()
method of the Element
interface returns the value of a specified attribute on the element.
If the given attribute does not exist, the value returned will either be null
or ""
(the empty string); see Non-existing attributes for details.
Syntax
getAttribute(attributeName)
Parameters
-
attributeName
is the name of the attribute whose value you want to get.
Return value
A string containing the value of attributeName
.
Examples
<div id="div1">Hi Champ!</div>
const div1 = document.getElementById("div1");
const exampleAttr = div1.getAttribute("id");
const align = div1.getAttribute("align");
Description
Lower casing
When called on an HTML element in a DOM flagged as an HTML document, getAttribute()
lower-cases its argument before proceeding.
Non-existing attributes
All modern web browsers return null
when the specified attribute does not exist on the specified element.
Retrieving nonce values
For security reasons, CSP nonces from non-script sources, such as CSS selectors, and .getAttribute("nonce")
calls are hidden.
let nonce = script.getAttribute("nonce");
Instead of retrieving the nonce from the content attribute, use the nonce
property:
let nonce = script.nonce;
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
getAttribute |
1 |
12 |
1 |
5 |
8 |
1 |
4.4 |
18 |
4 |
10.1 |
1 |
1.0 |