Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript - Recursive function to iterate through elements
    text
    copied!<p>I've just started reading up on JavaScript and I'm trying to write a small recursive function that would search through given nodes and return a list of values as a string.</p> <p>My HTML structure could be something like </p> <pre><code>&lt;div id="parentfolder"&gt;parentfolder1 &lt;div class ="item1"&gt;item1&lt;/div&gt; &lt;div class ="item2"&gt;item2&lt;/div&gt; &lt;div id="parentfolder"&gt;parentfolder2 &lt;div class ="item1"&gt;item1&lt;/div&gt; &lt;div class ="item2"&gt;item2&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>And Here is my Javascript function:</p> <pre><code>function jsoncreator(parentfolderclass){ var jstring = ''; //get first occurance of parent folder var parentfolder = document.getElementById(parentfolderclass); var childnodes = parentfolder.childNodes; for (property in childnodes){ jstring += property+ childnodes[property]; if(childnodes[property] === parentfolderclass){ jsoncreator(parentfolderclass); jstring += childnodes[property].value + '&lt;br&gt;'; } else{ //jstring += childnodes[i].value + '&lt;br&gt;'; } } document.write(jstring); } </code></pre> <p>All im getting back is </p> <pre><code>0[object Text]1[object HTMLDivElement]2[object Text]3[object HTMLDivElement]4[object Text]5[object HTMLDivElement]6[object Text]length7itemfunction item() { [native code] } </code></pre> <p>When I try to print the childnodes values, I get a bunch of undefined returns.</p> <p>If anybody could explain what I'm doing wrong, I'd really appreciate it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload