Ashwin
Ashwin

Reputation: 12411

nth-child selector, something weird

Fiddle is here - http://jsfiddle.net/ashwyn/a45ha/

HTML here -

<div class="parent">
    <div class="a">Class A</div>
    <div class="b">Class B1</div>
    <div class="b">Class B2</div>
    <div class="b">Class B3</div>
    <div class="b">Class B4</div>
    <div class="b">Class B5</div>
</div>​

Jquery here -

$(function(){
    $(".parent").children(".b:nth-child(2)").css("color", "red");
});​

Above I have written .b:nth-child(2) so why I am not able to select second element of class="b" ?

I want to highlight Class B2 as color:red, but I am getting Class B1 as color:red. What is the problem guys ? If that is how it is works then according to me it is a bug in this type of selector.

The fiddle is just to let you know guys what is my problem but in my real problem I have having nth-child(2) as nth-child(j + 1) where j plays other role as well and it cannot make it j+2.

Can anyone please let me know the workaround to highlight class B2

Upvotes: 0

Views: 122

Answers (3)

U.P
U.P

Reputation: 7442

why don't you use :eq(2) instead of :nth-child(2). In order to get B2 you would write:

$(".parent").children(".b:eq(1)").css("color", "red");

Update

For your original question why :nth-child(2) is not selecting the second child, I found the reason. On jQuery docs site i found:

The :nth-child(n) pseudo-class is easily confused with :eq(n), even though the two can result in dramatically different matched elements. With :nth-child(n), 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 (n+1)th one (n is 0-based) is selected.

So in your case

$(".parent").children(".b:nth-child(2)").css("color", "red");

the :nth-child(2) counts the children of .parent and returns only if the element is .b

Upvotes: 3

Behnam Esmaili
Behnam Esmaili

Reputation: 5967

as jquery documentation index for nth-child is not zero based.it starts from 1.

Upvotes: 0

sachleen
sachleen

Reputation: 31131

:nth-child() will select the nth child. So if you specify 2, it'll do the second. If you want the 3rd, specify 3.

See their example, too.

$("ul li:nth-child(2)")
John
Karl - 2nd!
Brandon

I don't understand why you can't make it j+2.

Upvotes: 0

Related Questions