mmcglynn
mmcglynn

Reputation: 7662

How do I use jQuery .each() to find a child's children?

Given many TABLE tags on a page, how do I select the TD childred on a selected table.

This is logical, but fails with this error:

Error: uncaught exception: Syntax error, unrecognized expression: [object Object]tr

My code

$(document).ready(function () {
    var selectedTable = $('table').eq('9');

    $(selectedTable).css('border','10px solid green');

    $(selectedTable + 'tr td').each(function(i) {
        $(this).css('border','10px solid blue');
    });

});

Upvotes: 8

Views: 42870

Answers (4)

jbabey
jbabey

Reputation: 46647

$(selectedTable).find('td').each(function (index, element) {
    ...
});

Upvotes: 25

Bojangles
Bojangles

Reputation: 101493

Use .find() to get the children of the table. The problem you're having is that selectedTable isn't a selector string, but an object. You can't concatenate an object with a string, which is why you get your error.

This should work fine:

$(document).ready(function () {
    var selectedTable = $('table').eq('9');

    $(selectedTable).css('border','10px solid green');

    $(selectedTable).find('tr td').each(function(i) {
        $(this).css('border','10px solid blue');
    });
});

Upvotes: 3

ScottE
ScottE

Reputation: 21630

selectedTable.find('tr td').each(function(i) {
        $(this).css('border','10px solid blue');
    });

You can also chain like the following:

selectedTable.css('border','10px solid green').find('tr td').each(function(i) {
  $(this).css('border','10px solid blue');
});

Also, you don't need to use $(selectedTable) again as your selector already returns a jquery object.

Upvotes: 3

SLaks
SLaks

Reputation: 887453

selectedTable is a jQuery object, not a string.
You can't use it in a selector.

Instead, you need to use jQuery's traversal API:

selectedTable.find('tr td')

Upvotes: 8

Related Questions