getAttribute() 函式會回傳該網頁元素的屬性。 如果該屬性不存在,其回傳值會是null或 "" (空字串); 詳見 Notes 。


var attribute = element.getAttribute(attributeName);


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


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

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


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() (en-US) 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 compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help! (en-US)
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 29 23 (Yes) (Yes) 6

DOM methods dealing with element's attributes:

Not namespace-aware, most commonly used methods Namespace-aware variants (DOM Level 2) DOM Level 1 methods for dealing with Attr nodes directly (seldom used) DOM Level 2 namespace-aware methods for dealing with Attr nodes directly (seldom used)
setAttribute (en-US) (DOM 1) setAttributeNS (en-US) setAttributeNode (en-US) setAttributeNodeNS (en-US)
getAttribute (DOM 1) getAttributeNS (en-US) getAttributeNode (en-US) getAttributeNodeNS (en-US)
hasAttribute (en-US) (DOM 2) hasAttributeNS (en-US) - -
removeAttribute (en-US) (DOM 1) removeAttributeNS (en-US) removeAttributeNode (en-US) -