简体   繁体   中英

selecting first td from all rows using css selector

Here is my html

<table id="mytable" >
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr >
            <td>1888</td>
            <td>Michael</td>
        </tr>

        <tr>
            <td>1886</td>
            <td>Bosco</td>
        </tr>

        <tr>
            <td>955</td>
            <td>Raj</td>
        </tr>
    </tbody>
</table>

i want to select first td from all rows

So output will be 1888, 1886, 955

I tried this table[id='mytable'] tr:nth-child but it throws error.

Can someone help?

To achieve what you want you need to change the selector you're using to: table[id='mytable'] tr td:first-child . This will select the first td in every tr in the table with the ID mytable

The code in the snippet is just an example of how to apply it

 $(document).ready(function() { $("table[id='mytable'] tr td:first-child").css({'background-color':'pink'}); }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="mytable" > <thead> <tr> <th>ID</th> <th>Name</th> </tr> </thead> <tbody> <tr > <td>1888</td> <td>Michael</td> </tr> <tr> <td>1886</td> <td>Bosco</td> </tr> <tr> <td>955</td> <td>Raj</td> </tr> </tbody> </table> 

Hope this helps!

You should use first-child selector on td elements:

#mytable td:first-child {
  background: red;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM