最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get only first level divs? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 6

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();
$("#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;
});
发布评论

评论列表(0)

  1. 暂无评论