title: How to select the highest matching descendants
body: <p>I'm working with HTML content where authors may set a class on particular elements, content might be dynamically inserted, and developers might have code that also applies the same class to select elements.   I need to prune the class from all but the highest descendants.  I have a recursive function that already does this by using querySelectorAll(selector) and for each match, it crawls up the tree, removing the descendant's class if any parent along the way has the same class.  It does this till it reaches the body element.  So, for a huge body of content, it's just one of several fairly intensive transformations.</p>
  
  <p>I'm hoping that I've overlooked a much faster way to do this, maybe a native function or lean selector expression.</p>
  
  <p>For example, in the following, I only want to keep two branches.  If I can find a generic way to just select those two, the nested branches' classes can be pruned much more quickly than a recursive check from every single match:</p>
  
  <pre><code>&lt;div class="content"&gt;
      &lt;div class="branch"&gt; &lt;!-- Keep this --&gt;
          &lt;div class="branch"&gt;
              &lt;div class="branch"&gt;&lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
      &lt;div&gt;
          &lt;div&gt;
              &lt;div class="branch"&gt; &lt;!-- Keep this --&gt;
                  &lt;div&gt;
                      &lt;div class="branch"&gt;&lt;/div&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Update: While working on a solution, I realized I don't have to use recursion and I can prune the <code>Array.from([selector results])</code> as I go.  So that speeds it up some, but I'm still thinking that I'm overlooking an obvious selector expression or missing out on a native function.  I also found node.contains(), but I don't see a great way to leverage that yet. </p>