How to iterate through all attributes in an HTML element?

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

Leave a Comment