Reputation: 44085
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);
Upvotes: 0
Views: 723
Reputation: 723508
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 every div
that's contained by (is a child of) some other element of #wrapper
or 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:
var id = $o1.children('div:nth-child(2)').attr('id');
Or as Nick Craver suggests, use the child selector >
to limit your contextual search to children of #wrapper
:
var id = $('> div:nth-child(2)', $o1).attr('id');
Upvotes: 1
Reputation: 10598
there are actually 4 instances of that selector:
var $o1 = $("#wrapper");
$("div:nth-child(2)",$o1).each(function () {
alert($(this).attr("id"));
});
Upvotes: 0