61

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)

0

6 Answers 6

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);
    }
}
Sign up to request clarification or add additional context in comments.

11 Comments

Works in Opera and Safari too.
This example isn't working for me. It appears that elem isn't defined. What am I doing wrong here?
@AndersonGreen If you think about it for a moment it will come to you.
@AndersonGreen The word "recursively" does not apear in the question. Interation does not imply recursion. You'll have to implement recursion yourself.
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.
|
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}`);
})

Comments

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.

Comments

1

More efficient

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

Comments

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>

1 Comment

Why do you copy? No need to Copy!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.