DEV Community

Cover image for How to get all the attributes of an element using JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to get all the attributes of an element using JavaScript?

Originally posted here!

To get all the attributes of a DOM element, we can use the attributes property on the element using JavaScript.

Let's say we have a h1 tag with custom attributes data-color and data-maxlength like this,

<h1 data-color="red" data-maxlength="50">Heading</h1>
Enter fullscreen mode Exit fullscreen mode

Let's get all the attributes using the attributes property on the element.

// first get the reference to h1 element
const h1 = document.querySelector("h1");

// get all attributes
// using attributes property
const h1TagAttributes = h1.attributes;

console.log(h1TagAttributes);
Enter fullscreen mode Exit fullscreen mode

The property returns the attributes as NamedNodeMap array-like Object.

So to make it easy let's map through each attribute using the for...of looping statement and get each attributes name and value.

// first get the reference to h1 element
const h1 = document.querySelector("h1");

// get all attributes
// using attributes property
const h1TagAttributes = h1.attributes;

// loop through each attribute
for (let attribute of h1TagAttributes) {
  console.log(attribute.name); // attribute name
  console.log(attribute.value); // attribute value
}
Enter fullscreen mode Exit fullscreen mode

See live example in JSBin.

Feel free to share if you found this useful 😃.


Top comments (0)