How to iterate through all attributes in an HTML element?

JavascriptHtmlDom

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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.

Solution 4 - Javascript

More efficient

Array.prototype.forEach.call(elm.attributes, attr => console.log(attr))

Solution 5 - Javascript

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>

Solution 6 - Javascript

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;"
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobin RodricksView Question on Stackoverflow
Solution 1 - JavascriptTomalakView Answer on Stackoverflow
Solution 2 - JavascriptLloydView Answer on Stackoverflow
Solution 3 - JavascriptN-ateView Answer on Stackoverflow
Solution 4 - JavascriptDanny RaufeisenView Answer on Stackoverflow
Solution 5 - JavascriptJens TörnellView Answer on Stackoverflow
Solution 6 - JavascriptSamuel PrevostView Answer on Stackoverflow