Javascript: find all "input" in a table

Is there a shorter way to write this in JavaScript?

var data = []; var table = document.getElementById( 'address' ); var rows = table.getElementsByTagName( 'tr' ); for ( var x = 0; x < rows.length; x++ ) { var td = rows[x].getElementsByTagName( 'td' ); for ( var y = 0; y < td.length; y++ ) { var input = td[y].getElementsByTagName( 'input' ); for ( var z = 0; z < input.length; z++ ) { data.push( input[z].id ); } } } 
+7
source share
3 answers

element.getElementsByTagName finds all descendants, not just children, therefore:

 <script type="text/javascript> var data = []; var table = document.getElementById( 'address' ); var input = table.getElementsByTagName( 'input' ); for ( var z = 0; z < input.length; z++ ) { data.push( input[z].id ); } </script> 
+7
source

Yes.

 var data = [], inputs = document.getElementById('address').getElementsByTagName('input'); for (var z=0; z < inputs.length; z++) data.push(inputs[z].id); 

Note that even in your longer version with three loops, you can also say:

 var rows = table.rows; // instead of var rows = table.getElementsByTagName('tr'); // and, noting that it returns <th> cells as well as <td> cells, // which in many cases doesn't matter: var tds = rows[x].cells; // instead of var tds = rows[x].getElementsByTagName('td'); 
+2
source

For modern browsers :)

 var table, inputs, arr; table = document.getElementById( 'test' ); inputs = table.querySelectorAll( 'input' ); arr = [].slice.call( inputs ).map(function ( node ) { return node.id; }); 

Live demo: http://jsfiddle.net/HHaGg/

So, instead of the for loop, I use the map method - each element of the array (each INPUT node) is replaced by its identification value.

Also note that `inputs.map(... does not work, since inputs is a inputs element - it is an object that looks like an array but not a standard one. To still use the map method on it, we just need to convert it to an array which for us is [].slice.call( inputs ) .

+1
source

All Articles