Saturday, October 27, 2012

jQuery - Difference between :eq() and :nth-child() selectors.


    In jQuery many times :nth-child(n)  pseudo-class selector is easily confused with :eq(n), even though the two can result in dramatically different matched elements.

   With :nth-child(n), first all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :eq(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the nth one is selected.

    In other worlds, with :nth-child(n), first all elements those are children are considered and among the children, nth child is considered then it’s checked if it matches the selector which is attached with :nth-child(n). On the other hand with :eq(n) first the attached selector is resolved to set of elements and among those elements nth element is selected independent of considering children or not.


    Also there is another important difference, that is :nth-child() is 1 indexed means indexing count starts with 1 so nth means actual nth one. While :eq() is 0 indexed with indexing starting with 0 so nth element is actually (n+1)th. This is so because jQuery's implementation of :nth-child(n) is strictly derived from the CSS specification and for all other selector expressions including :eq() however, jQuery follows JavaScript's "0-indexed" counting. 

   Let's see following simple example: 


<table>
          <tr><td>Table1-row1</td></tr>
          <tr><td>Table1-row2</td></tr>
          <tr><td>Table1-row3</td></tr>
</table>
<table>
          <tr><td>Table2-row1</td></tr>
          <tr><td>Table2-row2</td></tr>
          <tr><td>Table2-row3</td></tr>
          <tr><td>Table2-row4</td></tr>
</table>

In above tables $(“tr:nth-child(3)”) will select two elements :


         <tr><td>Table1-row3</td></tr>
And

        <tr><td>Table2-row3</td></tr>

While $(“tr:eq(3)”) will select only single element :


        <tr><td>Table2-row1</td></tr>
   
 Please try following fiddle also, run it and click a button to see what it selects. It also shows how :even and nth-child(even) are different.






No comments:

Post a Comment