Kevin
Kevin

Reputation: 1614

Jquery selector not selecting value

The following is my table and I am trying to select elements from within the table

<table id="DetailsGridViewDiv_Header" style="border: 1px solid;">
    <tbody>
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
            <th>D</th>
            <th>E</th>
            <th>F</th>
            <th>G</th>
            <th>H</th>
        </tr>
    </tbody>
</table>

This is how I am trying to extract the values from the table:

alert($("#DetailsGridViewDiv_Header > th:nth-child(3)").text());

It doesn't return any letter

Upvotes: 1

Views: 46

Answers (3)

Sean Kendle
Sean Kendle

Reputation: 3619

When you select something in jQuery it returns an array, so it may make more sense to use the eq() function to select the jQuery object (thanks, Rory!):

var $thArray = $("#DetailsGridViewDiv_Header").find("th");
alert($thArray.eq(2).text());

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337580

The issue is because you're using the direct descendant selector (>) and the th is not a direct descendant of the #DetailsGridViewDiv_Header. Remove that operator and it will work fine:

alert($("#DetailsGridViewDiv_Header th:nth-child(3)").text());

If you want to keep the descendant selector, you will need to follow the descendant elements in order:

alert($("#DetailsGridViewDiv_Header > tbody > tr > th:nth-child(3)").text());

Upvotes: 2

nicael
nicael

Reputation: 18995

th not a direct descendant of the table with id DetailsGridViewDiv_Header, so should be:

$("#DetailsGridViewDiv_Header th:nth-child(3)").text()

Upvotes: 1

Related Questions