Green Wizard
Green Wizard

Reputation: 3667

Select only direct descendant of body tag

<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

Answers (5)

vsync
vsync

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

Matteo Gariglio
Matteo Gariglio

Reputation: 522

If you know the order of their appeareance you can do:

 $(".container").eq(0);

where 0 is the position

Upvotes: 0

Hareesh
Hareesh

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

Tango Bravo
Tango Bravo

Reputation: 3309

Lots of ways, I suppose. With a limited understanding of constraints, something like:

$('body > div.container');

Should work

Upvotes: 3

bundacia
bundacia

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

Related Questions