tags:

views:

30

answers:

4

how do i get the child divs and put it in a array?

<div id="parent">
   <div id="child1"></div>
   <div id="child2"></div>
</div>

var array = $('#parent > div').... (im stuck).

thanks!

A: 

var divs = $('#parent > div')
for(i = 0;i < divs.length; i++)
{
    ...
}

lakhlaniprashant.blogspot.com
+4  A: 

Actually there is nothing wrong with your jQuery code. You should wrap it into the .ready() callback:

$(function(){
   var arr = $('#parent > div');
});

If you "really" want a a plain array you need to use .get()

$(function(){
   var arr = $('#parent > div').get();
});

For the array of the ID's, as you mentioned in your comment use:

var arr = $('#parent > div').map(function(){
    return this.id;
}).get();

Ref.: .map(), .get()

jAndy
i need the array of its ID's.
Martin Ongtangco
@Marting: see third example. `map()` will do it.
jAndy
A: 
$("#parent").children("div");
PeterWong
A: 

If you just wan't the id attributes as an array you can try this:

var ids = $.map($('#parent > div'), function(child) { return child.id; });

It utilizes the jQuery.map function which transforms one array to another.

korchev