jquery - Why is this nth-child returning an unexpected element? -
the html & jquery below , it's @ http://www.jsfiddle.net/4fwuu. expecting second child of 'wrapper' div id 'parent2'. returned id 'child1_1_1_2' don't expect.
i can proper div using $o1.children()[1]
wanted know why nth-child 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 context same .find()
, picks deepest descendants first before traveling dom tree. :nth-child()
not care parent if don't specify parent, every div
that's contained (is child of) other element of #wrapper
or inside gets selected.
the .children()
method, says on tin, limits selection element's children, matched child. use instead pass :nth-child()
selector so:
var id = $o1.children('div:nth-child(2)').attr('id');
or nick craver suggests, use child selector >
limit contextual search children of #wrapper
:
var id = $('> div:nth-child(2)', $o1).attr('id');
Comments
Post a Comment