8

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 );
            }
        }
    }
2
  • I added the script-tags only because I thought it might be necessary for highlighting. Commented Sep 10, 2011 at 13:38
  • When posting a question regarding DOM traversal, it's important to post the HTML markup you're using. That way, any confusion is eliminated. Commented Sep 10, 2011 at 18:05

3 Answers 3

8

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> 
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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.

3 Comments

Is this faster then the for loop?
Which is the last browser (the most modern browser) on which this doesn't work yet?
@sid IE8. Array.prototype.map is one of the new ES5 features.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.