Element: getAttribute() method
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
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 be null.
If you need to inspect the Attr node's properties, you can use the getAttributeNode() method instead.
Syntax
getAttribute(attributeName)
Parameters
attributeName-
The name of the attribute whose value you want to get.
Return value
A string containing the value of attributeName if the attribute exists, otherwise null.
Examples
<!-- example div in an HTML DOC -->
<div id="div1">Hi Champ!</div>
const div1 = document.getElementById("div1");
// <div id="div1">Hi Champ!</div>
const exampleAttr = div1.getAttribute("id");
// "div1"
const lang = div1.getAttribute("lang");
// null
Description
>Lower casing
When called on an HTML element in a DOM flagged as an HTML document,
getAttribute() lower-cases its argument before proceeding.
Decoded character references in attribute values
HTML character references in an attribute's source markup (for example, <, &, or <) are decoded by the HTML parser when the document is parsed, so getAttribute() returns the decoded value, not the original source.
Given:
<div id="example" data-payload="<b>hi</b>"></div>
calling document.getElementById("example").getAttribute("data-payload") returns the string "<b>hi</b>".
Treating the return value from getAttribute() as already-escaped HTML is unsafe. If you read an attribute that holds untrusted data and then assign it to innerHTML or insert it into the document as markup, any HTML references used to escape special characters will already be decoded, and the result can be exploited for cross-site scripting (XSS).
Use textContent (or another text-safe API) for untrusted data instead of innerHTML.
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");
// returns empty string
Instead of retrieving the nonce from the content attribute, use the
nonce property:
let nonce = script.nonce;
Specifications
| Specification |
|---|
| DOM> # ref-for-dom-element-getattribute①> |