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)
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.
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.
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With