Html code:
<table>
<tr>
<td>The first row</td> <td>The first row</td>
</tr>
<tr>
<td>The second row</td> <td>The second row</td>
</tr>
<tr>
<td>The third row</td> <td>The third row</td>
</tr>
<tr>
<td>The forth row</td> <td>The forth row</td>
</tr>
</table>
<hr>
<table>
<tr>
<td>The first row</td> <td>The first row</td>
</tr>
<tr>
<td>The second row</td> <td>The second row</td>
</tr>
<tr>
<td>The third row</td> <td>The third row</td>
</tr>
<tr>
<td>The forth row</td> <td>The forth row</td>
</tr>
</table>
jQuery code:
$(function () {
$("table:first tr").css("background", "#ffbbbb"); //work
$("table:last>tr").css("background", "#ffbbbb"); //not work
$("table:last").children("tr").css("background", "#ffbbbb"); //not work
});
Result: The background of the first table is changed, but the second table is not. Seems that the space selector worked, but the '>' and 'children()' selector doesn't, Why?
Working Example: https://jsfiddle.net/6knk67gd/1/
I have checked the usage of these two selectors, but still can't find any problem in my code. Please tell me how to use them correctly, thank you~
Even though we are not creating a tbody
, by default the dom structure will create it, so all tr
will a child of tbody/thead/tfooter
not the table
itself
Try
$("table:last > tbody > tr").css("background", "#ffbbbb");
The sign > means direct descendant and there's a tbody automatically generated between table and tr. Try this:
$("table:last > tbody > tr").css("background", "#ffbbbb");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With