title: Conversion of an unordered list to JSON
body: <p>I'm trying to build a JSON object from a UL element in Javascript.</p>
  
  <p>I have this list structure:</p>
  
  <pre><code>&lt;ul id="trainingmenu"&gt;
      &lt;li class="tmnode"&gt;&lt;span id="M5lx9n" class="tmname"&gt;menu 1&lt;/span&gt;
          &lt;ul&gt;
              &lt;li class="tmnode"&gt;&lt;span id="M66p48" class="tmname"&gt;menu 2&lt;/span&gt;
                  &lt;ul&gt;
                      &lt;li class="tmnode"&gt;&lt;span class="tmname" id="Mschr"&gt;menu 3&lt;/span&gt;
                      &lt;/li&gt;
                  &lt;/ul&gt;
              &lt;/li&gt;
              &lt;li class="tmnode"&gt;&lt;span id="Mu03e0" class="tmname"&gt;menu 4&lt;/span&gt;&lt;/li&gt;
          &lt;/ul&gt;
      &lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>This is the JS:</p>
  
  <pre><code>var treeObject = {};
  
      function treeHTML(element, object) {
          if (element.tagName=="UL") { element=element.firstChild; }
          object["id"] = element.firstChild.id;
          object["name"] = element.firstChild.innerHTML;
          var nodeList = element.getElementsByTagName('LI');
          if (nodeList[0]) {
              object["nodes"] = [];
              for (var i = 0; i &lt; nodeList.length; i++) {
                  object["nodes"].push({});
                  treeHTML(nodeList[i], object["nodes"][object["nodes"].length - 1]);
              }
          }
      }
      treeHTML(document.getElementById("trainingmenu"), treeObject);
      alert(JSON.stringify(treeObject));
  </code></pre>
  
  <p>..and this is the output I'm getting:</p>
  
  <pre><code>{"id":"M5lx9n","name":"menu 1","nodes":[{"id":"M66p48","name":"menu 2","nodes":[{"id":"Mschr","name":"menu 3"}]},{"id":"Mschr","name":"menu 3"},{"id":"Mu03e0","name":"menu 4"}]}
  </code></pre>
  
  <p>It's part-working and this is the format I want - picking out the id and name fields from the childNode of each LI element. But it's repeating nodes - menu 3 appears twice</p>
  
  <p>Here's a <a href="http://jsfiddle.net/Che95/" rel="nofollow">fiddle</a></p>
  
  <p>I've probably screwed up the recursion but having stared at it for 2 days haven't worked out how. Can anyone help?</p>