I have a problem with selecting an element in jQuery

I am using selectorgadget to help me select elements in a document. But when I used it in jQuery it didn't work. The nth-child selector doesn't seem to work for me.

<div id = "wrap">
<div class = "book">
    <div class = "chapter">
        <p class = "text">
            <table>
                <tbody>
                    <tr>
                        <td>Title</td>
                        <td>
                            <b>jQuery</b>
                        </td>
                    </tr>
                </tbody>
            </table>
        <p>
    </div>
</div>
</div>

      

HTML above. There is a lot of book class. The wrapper div is the wrapper that surrounded them. The selector gadget said that when I use:

$("#wrap tr:nth-child(1) b")

It should select the TD element with the tag <b>

. Therefore, he must select "jQuery".

I tried it but it didn't work. When I tried:

var query = $("#wrap tr:nth-child(1) b").text();
alert(query);

      

The browser sends an alert with no text. And when I tried:

var query = $("#wrap tr:nth-child(1) b").html();
alert(query);

      

The browser sends a NULL warning.

What's wrong?

-1


a source to share


5 answers


I've tried this with FF 3.0.10, jQuery 1.3.2, greasemonkey 0.8.2

var query = $("#wrap tr:nth-child(2) b").text();
returns "jQuery"

      



2 in nth-child () does the trick !! The index for nth-child starts at 1 not 0

+2


a source


You tried

changed, I didn't notice tr: nth-child at first, there is no 1 child tr in this table, but there is a td index at index 1



var query = $(".text td:nth-child(1) b").html();
alert(query);

      

0


a source


When testing your sample in Firefox 3 and IE8, I was able to return the text you expected using your selector after one tweak - I added the id "wrap" to your table element:

<table id="wrap">

      

Once this was added, your selector seemed to work fine. Is there a specific platform that you have encountered?

0


a source


I just tried my example code and it worked right away. Which version of jQuery are you using? It works in 1.3.2

Here's a working example: http://jsbin.com/uzuzu/edit

0


a source


You need nth-child (2) ,: nth-child (1) selects the title. Remember that: eq is 0-based and: nth-child () is 1. Blend!

0


a source







All Articles