Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery:how to use ">" and children() in table

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~

like image 255
xialu Avatar asked Mar 15 '23 08:03

xialu


2 Answers

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"); 
like image 78
Arun P Johny Avatar answered Mar 25 '23 03:03

Arun P Johny


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");
like image 38
Martin Verner Avatar answered Mar 25 '23 03:03

Martin Verner