跳转到主要内容

Element: getAttributeNode() method

{{APIRef("DOM")}}

The getAttributeNode() method of the {{domxref("Element")}}Element interface returns the specified attribute of the specified element, as an {{domxref("Attr")}}Attr node. It returns null if the element doesn't have an attribute with the given name.

This method is useful if you need the attribute's instance properties. If you only need the attribute's value, you can use the {{domxref("Element.getAttribute()", "getAttribute()")}} method instead.

Syntax

getAttributeNode(attrName)

Parameters

  • attrName
    • : A string specifying the name of the attribute. When called on an HTML element in a DOM flagged as an HTML document, the name is normalized to lowercase.

Return value

An Attr node for the attribute, or null if the element doesn't have an attribute with the given name.

[!NOTE]NOTE: The Attr node inherits from Node, but is not considered a part of the document tree. Common Node attributes like parentNode, previousSibling, and nextSibling are null for an Attr node. You can, however, get the element to which the attribute belongs with the {{domxref("Attr.ownerElement", "ownerElement")}}ownerElement property.

Examples

// html: <div id="top" />
const t = document.getElementById("top");
const idAttr = t.getAttributeNode("id");
console.log(idAttr.value); // "top"

Specifications

{{Specifications}}

Browser compatibility

{{Compat}}

See also