The html & jQuery is below and it’s also at http://www.jsfiddle.net/4fWUU. I am expecting to get the second child of ‘wrapper’ which is the div with id ‘parent2’. However the returned id is ‘child1_1_1_2’ which I don’t expect.
I can get the proper div using $o1.children()[1] but I wanted to know why nth-child is not working right.
Any ideas why?
<div id="wrapper">
<div id="parent1">
<div id="child1">
<div id="child1_1">
<div id="child1_1_1">
<div id="child1_1_1_1">
</div>
<div id="child1_1_1_2">
</div>
</div>
<div id="child1_1_2">
</div>
</div>
<div id="child1_2">
<div id="child1_2_1">
</div>
</div>
</div>
</div>
<div id="parent2">
</div>
</div>
var $o1 = $("#wrapper");
var id = $("div:nth-child(2)",$o1).attr("id");
alert(id);
Searching by context is the same as
.find(), which picks up the deepest descendants first before traveling up the DOM tree.:nth-child()does not care about the parent if you don’t specify a parent, thus everydivthat’s contained by (is a child of) some other element of#wrapperor anything inside gets selected.The
.children()method, as it says on the tin, limits the selection to your element’s children, so anything matched will always be a child. Use that instead but pass the:nth-child()selector like so:Or as Nick Craver suggests, use the child selector
>to limit your contextual search to children of#wrapper: