javascript - how to make output text inside nested div with jquery -
i have div inside div (nested div) , 1 button click , 1 textarea, when click button want output div in text,and add text textarea
example
<div id="container"> <div class="nested"> <div id="1"> <div class="nested"> <div id="3">helpx</div> <div id="4">helpy</div> </div> </div> <div id="2">helpz</div> </div> </div> when click button need output =nested(=nested(helpx)(helpy))(helpz)
my code :
$('#buttonclick').click(function(){ $('#container').find("div").each( function(index) { .... }); }); i hope can me. .
you have set condition check whether child nested or child has nested children, or simple div. use recursive function handle it:
$('#buttonclick').click(function(){ var findnest = function(ele) { // see if current item needs nested prefix var result = $(ele).hasclass("nested") ? '=nested(' : ''; $(ele).find(' > div').each(function(idx, item) { var $item = $(item); if ($item.hasclass("nested")) { // if current cheked item nested item, nested it. result += findnest($item); } else if ($(item).find(".nested").length > 0) { result += findnest(item); } else { // current check item simple div, add result += '(' + $(item).text() + ')'; } }); // decide tail var tail = $(ele).hasclass("nested") ? ')' : ''; return result + tail; }; var $container = $('#container'); var result = findnest($container); console.log(result); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <div id="container"> <div class="nested"> <div id="1"> <div class="nested"> <div id="3">helpx</div> <div id="4">helpy</div> </div> </div> <div id="2">helpz</div> </div> </div> <div id="buttonclick">click</div> if want give level limit, code can changed to:
$('#buttonclick').click(function(){ // inits var level_limit = 2; var currentlevel = 0; var findnest = function(ele) { // add 1 level @ start. ++currentlevel; // see if current item needs nested prefix var result = $(ele).hasclass("nested") ? '=nested(' : ''; $(ele).find(' > div').each(function(idx, item) { var $item = $(item); var $nestchilds = $(item).find(".nested"); if (currentlevel <= level_limit && ($item.hasclass("nested") || $nestchilds.length > 0)) { // if current cheked item nested item, or has child nest, go it. result += findnest($item); } else { // current check item simple div or level limit reached, // add div texts...(may need other process of text now.) result += '(' + $(item).text() + ')'; } }); // decrease level 1 before return. --currentlevel; // decide tail var tail = $(ele).hasclass("nested") ? ')' : ''; return result + tail; }; var $container = $('#container'); var result = findnest($container); console.log(result); });
Comments
Post a Comment