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

I have a 3x3 table.

I want to select each td on a specific line. (For example, the second line)

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

Above code sets only the 2nd row of the 1st column to red.

I expected it to change every td on the second line, but it seems like I'm missing something.

Why is the above code not working as expected?

( EDIT : I am using Chrome 13 with jQuery 1.7.1)

+4
source share
3 answers

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

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

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

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

+3
source

This can be simplified by using the standard DOM properties that work in every major browser, and for now, you aim it at the actual table you are interested in, and not at all the tables (which is what your current selector does). This will be faster and more reliable 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"; } 
+2
source

Maybe you set bg for the whole line 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"); 
0
source

Source: https://habr.com/ru/post/1397059/


All Articles