Javascript: find all "input" in a table
Is there a shorter way to write this in JavaScript?
var data = [];
var table = document.getElementById( 'address' );
开发者_如何学JAVA 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 );
}
}
}
element.getElementsByTagName
finds all descendants, not only children, so:
<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>
Yep.
var data = [],
inputs = document.getElementById('address').getElementsByTagName('input');
for (var z=0; z < inputs.length; z++)
data.push(inputs[z].id);
Note, 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');
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 a for
loop, I make use of the map
method - each array element (each INPUT node) is replaced with its ID value.
Also note that `inputs.map(...
doesn't work since inputs
is a NodeList element - it's an array-like object, but not an standard array. To still use the map
method on it, we just have to transform it into an array which is what [].slice.call( inputs )
does for us.
精彩评论