JQuery children loop XML -


using jquery , ajax, getting xml document , looping through document in attempt @ each level of xml tags/nodes, parent children , children of children respectively.

what have works written limit of children of children of children (not ideal).

the final application may have open ended number of children action to.

how can make account number of children without inefficiency?

i have tried making function basis of wish achieve @ each child level. not work expected, breaking script.

the function

function childx() {     $(this).children().each(function()     {        $("#output").append("<div id='"+(this).nodename+"'>"+(this).nodename+"</div><br />");     }); } 

the main script

  $(xml).find("recenttutorials").children().each(function()   {      $("#output").append("<div id='"+(this).nodename+"'>"+(this).nodename+"</div><br />");       $(this).children().each(function()     {        $("#output").append("<div id='"+(this).nodename+"'>"+(this).nodename+"</div><br />");        $(this).children().each(function()         {            $("#output").append("<div id='"+(this).nodename+"'>"+(this).nodename+"</div><br />");              $(this).children().each(function()             {                $("#output").append("<div id='"+(this).nodename+"'>"+(this).nodename+"</div><br />");              });          });      });     //alert((this).nodename);   });  

the easiest way use recursive function - is, function calls itself.

addchildren( $(xml).find("recenttutorials") );  function addchildren( $parent ) {     $parent.children().each( function( i, child ) {         $("#output").append(             "<div id='" + child.nodename + "'>" +                 child.nodename +             "</div><br />"         );         addchildren( $(child) );     }); } 

for interesting test case, try opening javascript console on page uses jquery - such 1 on right - , paste in similar code:

logchildren( $(document.body) );  function logchildren( $parent ) {     $parent.children().each( function( i, child ) {         console.log( child.nodename );         logchildren( $(child) );     }); } 

it print nodename every element in page.

btw recommend against using this , $(this) when use jquery.each(). instead, use explicit parameter names in examples. it's easier understand code way, , less error-prone too. part of reason childx() function didn't work @ all. references this in first line, when call function directly, this unlikely expect: unless you're using strict mode, this reference window object!


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -