W3cubDocs

/DOM

element.getAttribute

getAttribute() 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 Notes for details.

Syntax

var attribute = element.getAttribute(attributeName);

where

  • attribute is a string containing the value of attributeName.
  • attributeName is the name of the attribute whose value you want to get.

Example

var div1 = document.getElementById("div1");
var align = div1.getAttribute("align");

alert(align); // shows the value of align for the element with id="div1"

Notes

When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding.

Essentially all web browsers (Firefox, Internet Explorer, recent versions of Opera, Safari, Konqueror, and iCab, as a non-exhaustive list) return null when the specified attribute does not exist on the specified element and this is what the current DOM specification draft specifies. The old DOM 3 Core specification, on the other hand, says that the correct return value in this case is actually the empty string, and some DOM implementations implement this behavior. The implementation of getAttribute in XUL (Gecko) actually follows the DOM 3 Core specification and returns an empty string. Consequently, you should use element.hasAttribute() to check for an attribute's existence prior to calling getAttribute() if it is possible that the requested attribute does not exist on the specified element.

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
Basic support 29 Yes 23 Yes Yes 6
Mobile
Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android iOS Safari Samsung Internet
Basic support ? ? ? 23 ? ? ?

Specification

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/element/getAttribute