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
<a id="link" href="https://example.com" target="_blank" data-category="external">Link</a> <img id="photo" src="/img/photo.jpg" alt="Photo" width="300">
var link = document.querySelector("#link");
console.log(link.getAttribute("href")); // Outputs "https://example.com"
console.log(link.getAttribute("target")); // Outputs "_blank"
console.log(link.getAttribute("data-category")); // Outputs "external"
var img = document.querySelector("#photo");
console.log(img.getAttribute("alt")); // Outputs "Photo"
console.log(img.getAttribute("width")); // Outputs "300"
// Attribute that does not exist
console.log(link.getAttribute("title")); // Returns null
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.