开发者

get from one div all child divs id

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

The selector below gives only "dog": i n开发者_高级运维eed 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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜