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
why don’t you use
:eq(2)instead of:nth-child(2).In order to get B2 you would write:
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:So in your case
$(".parent").children(".b:nth-child(2)").css("color", "red");the
:nth-child(2)counts the children of.parentand returns only if the element is.b