title: DOM traversal without exluded elements
body: <p>I'm creating a simple script that traverses the DOM and returns a tree object with the elements found in the DOM. Recursive traversal itself is quite simple but I want/need to skip certain elements and include other elements. How do I do this?</p>
  
  <p>This is my HTML:</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;div data-element="from-here"&gt;
    &lt;div&gt;skip me&lt;/div&gt;
    &lt;div&gt;
      &lt;div data-element="awesome"&gt;awesome text&lt;/div&gt;
      &lt;div data-element="collect-me"&gt;
        awesome text
        &lt;div data-element="also-me"&gt;
          other text
          &lt;div class="but-not-me"&gt;...&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>And my recursive traversal code:</p>
  
  <pre class="lang-js prettyprint-override"><code>const root = document.querySelector('[data-element="from-here"]');
  
  function traverse(node) {
    return {
      element: node.dataset.element,
      children: Array.from(node.querySelectorAll(':scope &gt; div')).map(childNode =&gt; traverse(childNode)),
    };
  }
  
  traverse(root);
  </code></pre>
  
  <p>As you can see the code queries all div elements but I only need the elements with a <code>data-element</code> attribute. I can't just do `node.querySelectorAll(':scope > [data-element]') because that won't reach past the first div. </p>
  
  <p>This is the result I want:</p>
  
  <pre><code>{
    element: 'from-here',
    children: [
      {
        element: 'awesome',
        children: [],
      },
      {
        element: 'collect-me',
        children: [
          {
            element: 'also-me',
            children: [],
          }
        ]
      }
    ]
  }
  </code></pre>
  
  <p>Any help would be greatly appreciated!</p>