How to iterate through all attributes in an HTML element?
Asked Answered
S

6

60

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)

Slumber answered 6/5, 2009 at 6:39 Comment(0)
J
60

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);
    }
}
Jobye answered 6/5, 2009 at 6:48 Comment(11)
Works in Opera and Safari too.Seabrook
This example isn't working for me. It appears that elem isn't defined. What am I doing wrong here?Countermeasure
@AndersonGreen If you think about it for a moment it will come to you.Jobye
I tried using var elem = document.getElementById("Something");, but that didn't work either, as seen here.Countermeasure
@AndersonGreen This sample alerts id = Something for me, which is exactly what's supposed to happen. Did you expect something else?Jobye
@Jobye I thought it was supposed to recursively iterate through the attributes of all the sub-elements of the first element, since that's how I interpreted the question.Countermeasure
@AndersonGreen The word "recursively" does not apear in the question. Interation does not imply recursion. You'll have to implement recursion yourself.Jobye
You should avoid calling attributes so many times; cache it in a local variable!Eurypterid
@Marc-AndréLafortune Premature optimization. DOM interactions like this are blazingly fast. (Yes, I know caching makes them this faster, but this bit will very, very likely not be the bottleneck of the page.)Jobye
@Tomalak: Let's agree to disagree. Your algorithm is in O(n^2), where n is the number of attributes. If you don't change the O() of an algorithm, that's fine, but writing something in O(n) instead of O(n^2) is good practise, not premature, IMO.Eurypterid
I'm not sure if a for loop is complex enough to call it an algorithm. I am also not quite sure where you get the notion that this would take O(n²) time. elem.attributes.length is very probably O(1), elem.attributes[i] is definitely O(1) - so as I see it the whole thing is O(n). But even if I am wrong: It does not matter. If you call this for every element on your page you're doing it wrong anyway. Hell, even then it takes only 8ms for this page here on my rusty laptop. And that's with jQuery $.each(). In short: I couldn't care less about the runtime characteristics of this bit.Jobye
E
19

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}`);
})
Environs answered 22/11, 2016 at 10:18 Comment(0)
I
6

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.

Integrated answered 26/11, 2017 at 16:55 Comment(0)
H
1

More efficient

Array.prototype.forEach.call(elm.attributes, attr => console.log(attr))
Hideandseek answered 21/5, 2018 at 11:43 Comment(0)
S
1

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>
Shererd answered 8/8, 2020 at 9:39 Comment(1)
Why do you copy? No need to Copy!Refutative
R
0

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;"
}
Raki answered 2/3, 2022 at 18:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.