Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through all attributes in an HTML element?

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)

like image 447
Robin Rodricks Avatar asked May 06 '09 06:05

Robin Rodricks


People also ask

How do I iterate through an HTML element?

To iterate over the selected elements, you can use forEach() method (supported by most modern web browsers, not IE) or just use the plain old for-loop.

How do I get all attributes in HTML?

To get all of the attributes of a DOM element:Use the getAttributeNames() method to get an array of the element's attribute names. Use the reduce() method to iterate over the array. On each iteration, add a new key/value pair containing the name and value of the attribute.

How do I iterate through an HTML object in JavaScript?

To loop through all DOM elements: Use the getElementsByTagName() method to get an HTMLCollection containing all DOM elements. Use a for...of loop to iterate over the collection.


1 Answers

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);     } } 
like image 91
Tomalak Avatar answered Oct 12 '22 15:10

Tomalak