views:

30

answers:

2

I would like to detect all the elements insides a parent element and still check if the child has child elements and detect them also.

For Example:

<div id="first">
     <div id='second1'></div>
     <div id='second2'>
          <div id='third1'></div>
          <div id='third2'>
               <div id='fourth1'></div>
               <div id='fourth2'></div>
          </div>
          <div id='third3'></div>
     </div>
     <div id='second3'></div>
     <div id='second4'></div>
</div>

I want to know the list of all the id inside the #first and check each child if it has its child and keep this on going until I have complete list of all element.

I want this list in an array kinda in this pattern

array (
"body"=> {
           "first" => "second1", "second2" .............
         }
);
+2  A: 

Try this:

$("#first *")

You can use the children method to get the children

$("#first").children()

Add some recursion

function recursion ( elem, arr )
{
   var id = $(elem).attr('id');
   if ( id )
   {
     var children = arr[ id  ] = {};
     $(elem).children().each( function(){ recursion(this, children ) });
   }
}

var elements = {};
recursion ( $("#first"), elements );
console.log ( JSON.stringify( elements ) );

and you will get

 {"first":{"second1":{},"second2":{"third1":{},"third2":{"fourth1":{},"fourth2":{}},"third3":{}},"second3":{},"second4":{}}}

http://jsbin.com/udaje4/edit

Ghommey
@Ghommey, No, No, I want to hold them in an array, so that I can manipulate them seperately, not at once. thanks any way
Starx
@Starx: Does this work for you?
Ghommey
A: 

Another approach would be:

var childrens = {};
$('#first').children().each(function() {
    id = $(this).attr('id');

    if($('#'+id).children().size() > 0) {
        $('#'+id).children().each(function() {
            childrens[id] = {}
            childrens[id][$(this).attr('id')] = {};
        });
    } else childrens[$(this).attr('id')] = {};
});

alert(JSON.stringify(childrens));
realshadow
This won't display third level children will it?
Ghommey
No it wont, its just another approach, but in the end it would have to end as recursion either way :) Thats why you got +1 from me
realshadow