How to iterate through all attributes in an HTML element?

dom, html, javascript

Solution

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

Problem

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)

Original source