jquery - get All Grandchildren according to attributes' binding recursively -
<div data-id="123">123</div> <div data-id="120" data-parent="123">120</div> <div data-id="115" data-parent="123">115</div> <div data-id="240">240</div> <div data-id="245" data-parent="240">245</div> <div data-id="246" data-parent="240">246</div> <div data-id="247" data-parent="240">247</div> <div data-id="255" data-parent="245">255</div> <div data-id="256" data-parent="245">256</div>
we have above tree presented using 2 attributes :
data-id
data-parent
thus, terminology of child-parent not got via $().parent()
or $().children()
however ,
$.fn.treechildren=function(){ return $('div[data-parent='+$(this).attr('data-id')+']'); }
then :
$('[data-id=240]').treechildren() // [245,246,247]
issue :
this plugin retrieves children , not children , children of >children , ... on.
how grandchildren expected result of $('[data-id=240]').treechildren()
[245,246,247,255,256]
not [245,246,247]
known following algo didn't work :
$.fn.treegrchildren=function(){ if($('div[data-parent='+$(this).attr('data-id')+']').treechildren().length){ return $('div[data-parent='+$(this).attr('data-id')+']').treegrchildren(); }else{ return $('div[data-parent='+$(this).attr('data-id')+']'); } }
fiddle
your code retrieves divs with: data-parent="240"
change these 2 line this:
<div data-id="255" data-parent="240">255</div> <div data-id="256" data-parent="240">256</div>
http://jsfiddle.net/xabgazk3/1/
or this:
$('#results').append( $('[data-id=240]').treechildren().clone()) $('#results').append( $('[data-id=245]').treechildren().clone())
http://jsfiddle.net/xabgazk3/2/
there no childrens or parents in html code of now. children() traverse single level down dom tree. traverse down multiple levels (to return grandchildren or other descendants), use find() method.
Comments
Post a Comment