is there a way to join 2 NodeLists returned by 2 calls of document.getElementsByTagName?
Say, I have the following code
var inputs = documentElement.getElementsByTagName('input'); var selects = document.getElementsByTagName('select');
I want to loop through the results. Is it possible in one loop?
Thank you in advance!
A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes). HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number. An HTMLCollection is always a live collection.
childNodes and methods such as document. querySelectorAll() . Note: Although NodeList is not an Array , it is possible to iterate over it with forEach() . It can also be converted to a real Array using Array.
So we can convert the nodelist to an array and create a new array of indexes as follows: const indexArr= [...list]. map( element => return [...list]. indexOf(element) );
Seems like you can use the same Array.prototype.slice.call that makes the args array-like object become an array. (See here)
var inputs = document.getElementsByTagName('input'); var selects = document.getElementsByTagName('select'); inputs = Array.prototype.slice.call(inputs); selects = Array.prototype.slice.call(selects); var res = inputs.concat(selects); alert(res.length);
You can't join them, but you can still loop through them sequentially in one loop like this:
for ( var i = 0; i < inputs.length + selects.length; i++ ) { var element = ( i < inputs.length ) ? inputs[i] : selects[i-inputs.length]; }
Alternatively, using jQuery, you could select them all in one go:
$('input, select')
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