title: jQuery - Parse DOM and create a tree structure (composite pattern)
body: <p>I am parsing the DOM, and I want to <strong><em>extract the hierarchy</em></strong> of all elements  that match a certain selector, lets say <code>$('[data-node]')</code>, into a JavaScript object tree structure.  I have failed to find a standard jQuery way of doing this.  Using jQuery.find() seems to return a flat list.  Perhaps I have just missed something obvious?</p>
  
  <p>For example, I would like to parse this:</p>
  
  <pre><code>&lt;div data-node="root"&gt;
     &lt;div class="insignificant-presentation"&gt;
          &lt;div&gt;
              &lt;div data-node="interestingItem"&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;div&gt;
      &lt;div data-node="anotherInterestingItem"&gt;
          &lt;div data-node="usefulItem"&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>And create a structure in JavaScript like this:</p>
  
  <pre><code>[
    {
      "node": "root",
      "children": [
        {
          "node": "interestingItem",
          "children": []
        },
        {
          "node": "anotherInterestingItem",
          "children": [
            {
              "node": "usefulItem",
              "children": []
            }
          ]
        }
      ]
    }
  ]
  </code></pre>