Sometimes, we want to iterate through all attributes in an HTML element with JavaScript.
In this article, we’ll look at how to iterate through all attributes in an HTML element with JavaScript.
Iterate Through All Attributes in an HTML Element with JavaScript
To iterate through all attributes in an HTML element with JavaScript, we can loop through the attributes property of the element with the for-of loop.
For instance, if we have the following element:
<div style='width: 100px' class='foo' id='bar'>
</div>
Then we can loop through the attribute values of it by writing:
const elem = document.querySelector('div')
for (const a of elem.attributes) {
console.log(a.name, a.value);
}
We select the div with:
const elem = document.querySelector('div')
Then we use the for-of loop with the elem.attributes value.
We get the name property to get attributer name, and the value property returns the attribute value.
So we get:
'style' 'width: 100px'
'class' 'foo'
'id' 'bar'
from the console log.
Conclusion
To iterate through all attributes in an HTML element with JavaScript, we can loop through the attributes property of the element with the for-of loop.