Cankut
Cankut

Reputation: 689

How to select cells of a specific row using nth-child

I have a 3x3 table.

I want to select each td within a specific row. (2nd row for example)

$('table > tbody > tr:nth-child(2) > td').css("background-color","red");

Above code sets only 2nd rows 1st column to red.

I expected it to modify each td in 2nd row but seems i'm missing something.

Why does above code doesn't work as expected?

(EDIT: I'm using Chrome 13 with jquery 1.7.1)

Upvotes: 4

Views: 12178

Answers (3)

Tim Down
Tim Down

Reputation: 324587

You could simplify this using standard DOM properties that work in every major browser and while you're at it target it to the actual table you're interested in rather than all tables (which is what your current selector does). This will run faster and more reliably than the jQuery equivalent.

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

var cells = document.getElementById("your_table_id").rows[1].cells;
for (var i = 0, len = cells.length; i < len; ++i) {
    cells[i].style.backgroundColor = "red";
}

Upvotes: 2

Rob W
Rob W

Reputation: 349032

Chrome seems to be bugged again View this demo in Chrome (observed bug in Chromium 17).

Instead of > td, you can use .children(), which is equivalent:

$('table > tbody > tr:nth-child(2)').children().css("background-color","red");

Demo: http://jsfiddle.net/kYZWY/2/

Upvotes: 4

Oybek
Oybek

Reputation: 7243

May be you'll set the bg to the whole row like this

$('table > tbody > tr:nth-child(2)').css("background-color","red");

This approach also gives an identical result

$('table > tbody > tr:nth-child(2)').children().css("background-color","red");

Upvotes: 0

Related Questions