Reputation: 3667
<body>
<div>
<div class='container'></div>
</div>
<div class='container'></div>
</body>
How can I get the second div
named container which is a direct descendant of body with jquery? I should not select it based on no.of the child. I cannot rely on the number of divs
present in the body.
Upvotes: 0
Views: 208
Reputation: 130245
ordered by selector speed: (for your specific DOM example)
$(document.body).find('> .container')
$(document.body).find('.container:last')
$('.container:eq(1)')
$('.container:last')
I didn't sepcifically used div.container
since it's much slower selector than just .container
Upvotes: 0
Reputation: 522
If you know the order of their appeareance you can do:
$(".container").eq(0);
where 0 is the position
Upvotes: 0
Reputation: 6900
<body>
<div>
<div class='container'></div>
</div>
<div class='container second-container'></div>
</body>
you can have multiple classes
$(".second-container").css();
Upvotes: 0
Reputation: 3309
Lots of ways, I suppose. With a limited understanding of constraints, something like:
$('body > div.container');
Should work
Upvotes: 3
Reputation: 1036
Use '>' in the css selector so you know you're getting the div.container nested directly in the outer div.
$('body > div.container')
JSFiddle here: http://jsfiddle.net/p2P2f/1/
Upvotes: 0