Dr. Chocolate
Dr. Chocolate

Reputation: 2165

How to iterate through a series of jquery elements and each of their subelements?

If I have a bunch of divs with a bunch of sub elements under each div.

I need an array or hash of each div as the key and a hash or array of the subelements as the value.

<div class = "something">
    <span class = "subelem">
    ....other elements
</div>

<div class = "something">
    <span class="subelem"> 
    ....other elements

. .
.

How to I access each element such that I can get a data structure like this:

x = mycollection[0]['subelem'] 

My idea was $('something').each(function(.....but I don't know where to go from here or even if this is correct.

Upvotes: 0

Views: 28

Answers (1)

Okku
Okku

Reputation: 7819

I'm not sure if x = mycollection[0][0]=subelem element was what you wanted. but this will give you that:

var mycollection=new Array();
$(".something").each(function(i){
    mycollection[i]=new Array();
    $(this).children().each(function(j){
       mycollection[i][j]=$(this); 
    });
});

If you want everything in onedimensional array, use:

var mycollection=new Array();
$(".something").each(function(i){
    $(this).children().each(function(){
       mycollection.push($(this)); 
    });
});

Upvotes: 1

Related Questions