Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

JavaScript Dictionary

  1. Home
  2. JavaScript Dictionary
  3. HTML Element .getAttribute()

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

ParameterDescription
attributeNameThe 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

Chrome Chrome
49+
Supported in all versions
Firefox Firefox
57+
Supported in all versions
Safari Safari
18+
Supported in all versions
Edge Edge
80+
11 or earlier ×
IE IE
11+
4 or earlier ×
Opera Opera
48+
7 or earlier ×
iOS Safari iOS Safari
18+
Supported in all versions
Android Browser Android Browser
37+
4 or earlier ×
Chrome Android Chrome Android
36+
17 or earlier ×
Firefox Android Firefox Android
79+
3 or earlier ×

If you find any errors or copyright issues, please .