Randel Ramirez
Randel Ramirez

Reputation: 3761

How to select the first element inside a td using jquery?

Here is what my html looks like:

<table border="1">
        <th></th>
        <th>ID</th>
        <th>Name</th>
        <tr>
            <td><input type="button" value="btn1"><input type="button" value="btn2"></td>
            <td>22</td>
            <td>Hello</td>
        </tr>
        <tr>
            <td><input type="button" value="btn1"><input type="button" value="btn2"></td>
            <td>25</td>
            <td>HTML</td>
        </tr>
        <tr>
            <td><input type="button" value="btn1"><input type="button" value="btn2"></td>
            <td>45</td>
            <td>CSS</td>
        </tr>

    </table>

Based on this structure of the html, which is being emitted by asp.net I want to add class on the first btn only of each row.

I tried using this but what happen is that even the second button of the td is also being selected:

 $(function () {

            $t = $('#GridView1 td').children().addClass('first');


        })

Sir/Ma'am your answers would be of great help. Thank you++

Upvotes: 2

Views: 4449

Answers (3)

sandeepKumar
sandeepKumar

Reputation: 811

$("tr > td").addClass('first');

Upvotes: 0

user1726343
user1726343

Reputation:

If I understand correctly, you need to select the first input in the first td in each tr. Try:

$("#GridView1 tr > td:nth-child(1) > input:nth-child(1)").addClass("first");

Of course, the less strict but more concise

$("#GridView1 input:nth-child(1)").addClass("first");

could also be used, but this assumes you aren't using inputs anywhere else in your table.

DEMO

Upvotes: 8

Ahmed D. Sherif
Ahmed D. Sherif

Reputation: 618

$("tr > td:first").addClass('first');

Upvotes: 0

Related Questions