Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 483
user1184100 Avatar asked Apr 10 '12 11:04

user1184100


3 Answers

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();
like image 127
Rory McCrossan Avatar answered Oct 11 '22 22:10

Rory McCrossan


$("#content > div")

Like this. You can get array of div's like this

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

See in jsfiddle http://jsfiddle.net/DsyzV/

like image 21
Chuck Norris Avatar answered Oct 11 '22 23:10

Chuck Norris


Use:

$("#content > div").each(function() {
  var divId = this.id;
});
like image 29
kgiannakakis Avatar answered Oct 11 '22 21:10

kgiannakakis