user1184100 user1184100 - 4 months ago 8
HTML Question

How to get only first level divs?

I have a div with an id of

content
and I want to get the
id
of the first level
div
elements, eg.
box1
,
box2
,
box3
. How can this be done ?

<div id="content">
<div id="box1" class="box1class">
<div>...</div>
</div>
<div id="box2" class="box1class">
<div>...</div>
</div>
<div id="box3" class="box1class">
<div>...</div>
</div>
</div>

Answer

Use the > child seelctor.

var ids = [];
$("#content > div").each(function() {
    ids.push(this.id);
});

You could shorten this further by using map():

var ids = $("#content > div").map(function() {
    return this.id;
}).get();
Comments