lolalola
lolalola

Reputation: 3823

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 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

Upvotes: 0

Views: 4653

Answers (4)

rahul
rahul

Reputation: 187020

Use .map() here

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

Working demo

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816262

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();

Upvotes: 7

Teneff
Teneff

Reputation: 32148

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')

Upvotes: 0

balexandre
balexandre

Reputation: 75073

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

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

});

example in JSBin

Upvotes: 0

Related Questions