I am trying to loop through all the elements retruned from getElementsByTagName("input")
using forEach. Any ideas why this does not work in FF, Chrome or IE?
<html> <head> </head> <body> <input type="text" value="" /> <input type="text" value="" /> <script> function ShowResults(value, index, ar) { alert(index); } var input = document.getElementsByTagName("input"); alert(input.length); input.forEach(ShowResults); </script> </body> </html>
After selecting elements using the querySelectorAll() or getElementsByTagName() , you will get a collection of elements as a NodeList . 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.
getElementsByTagName - the method name itself implies that it will return multiple elements - i.e. an array. The method always returns an array, with the length equal to the number of matching elements. As such you must always access the elements by the index of the element in the array.
The getElementsByTagName() method in HTML returns the collection of all the elements in the document with the given tag name. To extract any info just iterate through all the elements using the length property. Syntax: var elements = document.
You need to convert the nodelist to array with this:
<html> <head> </head> <body> <input type="text" value="" /> <input type="text" value="" /> <script> function ShowResults(value, index, ar) { alert(index); } var input = document.getElementsByTagName("input"); var inputList = Array.prototype.slice.call(input); alert(inputList.length); inputList.forEach(ShowResults); </script> </body> </html>
or use for loop.
for(let i = 0;i < input.length; i++) { ShowResults(input[i].value); }
and change ShowResults function to:
function ShowResults(value) { alert(value); }
Why do we need to do that?
Some objects in JavaScript look like an array, but they aren’t one. That usually means that they have indexed access and a length property, but none of the array methods. Examples include the special variable arguments, DOM node lists, and strings. Array-Like Objects and Generic Methods gives tips for working with array-like objects. source
UPDATE for 07.10.2019
Nowdays with ES6 you can use [...inputList].forEach
, or Array.from(inputList)
Yay, ES6:
const children = [...parent.getElementsByTagName('tag')]; children.forEach((child) => { /* Do something; */ });
MDN Doc for Spread Operator (...
)
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