How to get all attributes from a HTML element with JavaScript?

Sometimes, we want to get all attributes from a HTML element with JavaScript.

In this article, we’ll look at how to get all attributes from a HTML element with JavaScript.

How to get all attributes from a HTML element with JavaScript?

To get all attributes from a HTML element with JavaScript, we can use the attributes property of the element.

For instance, we write

const elem = document.querySelector("[name=test]");
const attrs = [...elem.attributes].map(
  (attr) => attr.nodeName
);

console.log(attrs);

to select the element with querySelector.

And then we get the attributes with elem.attributes.

Next, we spread the entries of attributes NodeMap into an array.

And we get the name of each attribute with nodeName.

Conclusion

To get all attributes from a HTML element with JavaScript, we can use the attributes property of the element.