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

javascript - get from one div all child divs id - Stack Overflow

programmeradmin0浏览0评论

How do I get all div IDs in children of "test" div?

The selector below gives only "dog": i need get "dog", "cat", "drig", for example.

var all = $(".test div").attr("id");
$("div").text(all);

<div class="test">
    <div id="dog"></div>
    <div id="cat"></div>
    <div id="drig"></div>
</div>

Thanks

How do I get all div IDs in children of "test" div?

The selector below gives only "dog": i need get "dog", "cat", "drig", for example.

var all = $(".test div").attr("id");
$("div").text(all);

<div class="test">
    <div id="dog"></div>
    <div id="cat"></div>
    <div id="drig"></div>
</div>

Thanks

Share Improve this question edited Mar 25, 2011 at 8:08 dianovich 2,28721 silver badges34 bronze badges asked Mar 25, 2011 at 8:04 lolalolalolalola 3,82320 gold badges64 silver badges98 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

If you mean all the direct descendants of the element, than you have to change your selector to $(".test > div") (it's the child selector). If you want to select all descendants, then you can leave it as it is.

Using .map(), you can create an array of IDs:

var all = $(".test > div").map(function() {
    return this.id;
}).get();

Use .map() here

var idArray = $("div.test > div").map(function(){
    return this.id;
}).get();

Working demo

$(".test div").each( function() {

   console.log( $(this).attr("id") );

});

example in JSBin

if you need all divs in .test

$('div.test div)

but if you have

<div class="test">
    <div id="dog"></div>
    <div id="cat"></div>
    <div id="drig">
            <div id="mouse"></div>
    </div>
</div>

and you don't need #mouse

$('div.test > div')

发布评论

评论列表(0)

  1. 暂无评论