HTML Element .getAttribute()
| Since: | DOM Level 1(1998) |
|---|
Returns the value of a specified attribute on an HTML element as a string. If the attribute does not exist, it returns null.
Syntax
var value = element.getAttribute("attributeName");
Parameters
| Parameter | Description |
|---|---|
| attributeName | The name of the attribute whose value you want to retrieve, specified as a string. Case-insensitive. |
Return Value
Returns the value of the specified attribute as a string. If the attribute does not exist, returns null.
Sample Code
sample_getAttribute.html
<a id="link" href="https://capsulecorp.example.com" target="_blank" data-character="goku">Son Goku's Profile</a> <img id="avatar" src="/img/vegeta.jpg" alt="Vegeta" width="200"> <input id="power" type="number" value="9000" min="0" max="99999">
sample_getAttribute.js
// Pattern 1: Get standard attribute values
var link = document.getElementById("link");
console.log(link.getAttribute("href")); // Outputs "https://capsulecorp.example.com"
console.log(link.getAttribute("target")); // Outputs "_blank"
// Pattern 2: Get a data-* (custom data) attribute
console.log(link.getAttribute("data-character")); // Outputs "goku"
// Pattern 3: Get src, alt, and other image attributes
var avatar = document.getElementById("avatar");
console.log(avatar.getAttribute("src")); // Outputs "/img/vegeta.jpg"
console.log(avatar.getAttribute("alt")); // Outputs "Vegeta"
console.log(avatar.getAttribute("width")); // Outputs "200" (always returned as a string)
// Pattern 4: A missing attribute returns null
console.log(link.getAttribute("title")); // Returns null
// Pattern 5: Check for null before using the value
var title = link.getAttribute("title");
if (title !== null) {
console.log("title value: " + title);
} else {
console.log("The title attribute does not exist."); // Outputs when the attribute is missing.
}
Overview
element.getAttribute() is a method that retrieves the value of an HTML element's attribute as a string. It works with standard attributes such as href, src, and class, as well as data-* attributes (custom data attributes).
To set an attribute value, use element.setAttribute().
Note that some properties (such as value and checked) can differ between HTML attributes and DOM properties. When reading the current value of a form field, it is more reliable to use the DOM property element.value directly rather than getAttribute("value").
element.getAttribute() is covered in more detail in the tutorial article Identify elements by ID and manipulate their attributes. Check it out if you're interested.
Browser Compatibility
4 or earlier ×
7 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.