How to iterate through all attributes in an HTML element?
Solution 1:
This would work in IE, Firefox and Chrome (can somebody test the others please? — Thanks, @Bryan):
for (var i = 0; i < elem.attributes.length; i++) {
var attrib = elem.attributes[i];
console.log(attrib.name + " = " + attrib.value);
}
EDIT: IE iterates all attributes the DOM object in question supports, no matter whether they have actually been defined in HTML or not.
You must look at the attrib.specified
Boolean property to find out if the attribute actually exists. Firefox and Chrome seem to support this property as well:
for (var i = 0; i < elem.attributes.length; i++) {
var attrib = elem.attributes[i];
if (attrib.specified) {
console.log(attrib.name + " = " + attrib.value);
}
}
Solution 2:
Another method is to convert the attribute collection to an array using Array.from
:
Array.from(element.attributes).forEach(attr => {
console.log(`${attr.nodeName}=${attr.nodeValue}`);
})
Solution 3:
In case anyone is interested in a filtered version, or is trying to build CSS attribute selectors, here you go:
let el = document.body;
Array.from(el.attributes)
.filter(a => { return a.specified && a.nodeName !== 'class'; })
.map(a => { return '[' + a.nodeName + '=' + a.textContent + ']'; })
.join('');
//outputs: "[name=value][name=value]
You can certainly remove the join to retreive an array or add a filter for "style" since in most web applications the style tag is widely manipulated by widgets.