Reputation: 113956
I need the JavaScript code to iterate through the filled attributes in an HTML element.
This Element.attributes ref says I can access it via index, but does not specify whether it is well supported and can be used (cross-browser).
Or any other ways? (without using any frameworks, like jQuery / Prototype)
Upvotes: 60
Views: 48472
Reputation: 1104
This is quite an old question, but reacting to @N-ate answer, here is a version following the same functional programming approach and that returns a JS Object which keys are the attribute names, and which values are the attributes' associated values:
Array.from(element.attributes)
.filter(a => a.specified)
.map(a => ({[a.nodeName]: a.nodeValue}))
.reduce((prev, curr) => Object.assign(prev || {}, curr))
This turns:
<div class="thingy verse" id="my-div" style="color: red;"><p>Hello</p></div>
Into
{
class: "thingy verse",
id: "my-div",
style: "color: red;"
}
Upvotes: 0
Reputation: 24748
The most simple approach is to use spread operator.
const el = document.querySelector('div');
[...el.attributes].forEach((attr) => {
console.log(attr.name + ' = ' + attr.value);
});
<div class="foo" id="bar"></div>
Upvotes: 1
Reputation: 8396
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}`);
})
Upvotes: 19
Reputation: 993
More efficient
Array.prototype.forEach.call(elm.attributes, attr => console.log(attr))
Upvotes: 1
Reputation: 6926
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.
Upvotes: 6
Reputation: 338158
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);
}
}
Upvotes: 60