Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript NodeList

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!

like image 979
Dasha Salo Avatar asked May 27 '09 09:05

Dasha Salo


People also ask

What is a NodeList in JavaScript?

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.

Is NodeList same as an array?

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.

How do I find NodeList index?

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


2 Answers

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); 
like image 200
Simon Avatar answered Sep 17 '22 12:09

Simon


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') 
like image 35
Mario Menger Avatar answered Sep 17 '22 12:09

Mario Menger