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" .............
}
);
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
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));
精彩评论