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>
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>
Share
edited Jul 6, 2016 at 6:44
Rory McCrossan
338k41 gold badges320 silver badges351 bronze badges
asked Apr 10, 2012 at 11:02
user1184100user1184100
6,89430 gold badges84 silver badges122 bronze badges
3
- possible duplicate of Selecting only first level element, not child elements with the same element name – Curtis Commented Apr 10, 2012 at 11:06
-
1
Why do you need the IDs? Please tell me it's not so you can say
$('#' + id)
– sorpigal Commented Apr 10, 2012 at 11:07 - @Sorpigal I wouldn't be surprised. The amount of redundant code people write with jQuery is mind-boggling... – Niet the Dark Absol Commented Apr 10, 2012 at 11:12
3 Answers
Reset to default 6Use 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();
$("#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/DsyzV/
Use:
$("#content > div").each(function() {
var divId = this.id;
});