English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML DOM Attribute Object

Attr object

The Attr object represents attributes in the Element object.

HTML attributes always belong to HTML elements.

In most DOM methods, you may retrieve attributes directly in the form of a string (for exampleElement .getAttribute(), but some functions (such as Element.getAttributeNode()) or iterate over the methods of the given Attr type.

NamedNodeMap object

The NamedNodeMap object represents an unordered collection of Attr objects.

Nodes in the NamedNodeMap can be accessed by name or index number.

Attribute and method

Attribute/MethodDescription
attr.isIdReturns true if the attribute type is Id; otherwise, returns false
attr.nameReturns the name of the attribute
attr.valueSets or returns the value of the attribute
attr.specifiedReturns true if the attribute is specified, otherwise returns false
  
nodemap.getNamedItem()Returns the specified attribute node from the NamedNodeMap
nodemap.item()Returns the attribute node at the specified index in the NamedNodeMap
nodemap.lengthReturns the number of attribute nodes in the NamedNodeMap
nodemap.removeNamedItem()Delete the specified attribute node
nodemap.setNamedItem()Set the specified attribute node (by name)

Example

This example displays all attribute names of the IMG element:

var attrList = document.querySelector("img").attributes;
var text = "";
   
for (let x = 0; x < attrList.length;++) {
    text += attrList[x].name + "<br>";
}
Test and see‹/›

This example displays all attribute values of the IMG element:

var attrList = document.querySelector("img").attributes;
var text = "";
   
for (let x = 0; x < attrList.length;++) {
    text += attrList[x].value + "<br>";
}
Test and see‹/›

This example changes the value of the src attribute of the IMG element:

var image = document.querySelector("img");
image.getAttributeNode("src").value = "heart.jpg";
Test and see‹/›