Search code examples
javascriptjquerychildren

How do I use the nth-child selector with jquery's child selector?


This works fine:

$("#element").find("> tr > td > i > a")

But I'm trying to use the nth-child selector to say that I want a specific numbered child. For example, I want:

$("#element").find("> tr > td > i > a:nth-child(3)")

I'm not getting any results. Does anyone have any ideas on how I could select all the nth numbered children? Thanks in advance!


Solution

  • Firstly, this unless there's a great need to do direct descendant (the >) selectors, I don't see the need of including them, you can appropriately shorten your CSS selector too:

    //Select 3rd <a> tag, within the context of #element td
    $('a:nth-child(3)', '#element td');
       //or
    $('#element td a:nth-child(3)')
    

    Fiddle: http://jsfiddle.net/KGWuK/

    Although, currently your selector provided with the question will only work if your HTML structure is:

     <td>
         <i>
             <a>One</a>
             <a>Two</a>
             <a>Three</a>
         </i>
     </td>    
    

    Which isn't a very advisable style of markup. That's because the original selector is selecting <a> tags of those that a direct child of the <i>