HTML DOM Element attributes

Examples

How many attributes does the <img> element have:

let numb = document.getElementById("myImg").attributes.length;
Try it Yourself »

Display all attributes of an <img> element:

const nodeMap = document.getElementById("myImg").attributes;
let text = "";
for (let i = 0; i < nodeMap.length; i++) {
  text += nodeMap[i].name + " = " + nodeMap[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
Try it Yourself »

More examples below.


Description

The attributes property returns a collection of attributes in an element.

The attributes property returns a NamedNodeMap.


NamedNodeMap

A NamedNodeMap is an array-like unordered collection of an element's attributes.

In other words: a NamedNodeMap is a list of Attr objects.

A NamedNodeMap has a length property that returns the number of nodes.

The nodes can be accessed by name or index numbers. The index starts at 0.



Syntax

node.attributes

Return Value

Type Description
NamedNodeMapA collection of attribute objects.


More Examples

How many attributes does the <button> element have:

let numb = document.getElementById("myButton").attributes.length;
Try it Yourself »

Get the name of a <button> element's second (index 1) attribute:

let attr = document.getElementById("myBtn").attributes[1].name;
Try it Yourself »

Browser Support

element.attributes is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.