I have a collection of DOM elements that was created using RegEx on nodes to look for a particular keyword. This collection contains all sorts of HTML elements.

How can such a collection be narrowed down to contain only top level elements?

-- Essentially, given collection\_A create a collection\_B that does not contain elements that may be children of other elements in the collection.

For example:

```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="div_1"> no key here </div>
<div class="div_2"> no key here </div>
<div class="div_3"> contains {key}
  <div class="div_a"> no key here </div>
  <div class="div_b"> contains {key} </div>
  <div class="div_c"> no key here </div>
  <div class="div_d"> contains {key}
    <div class="div_e"> contains {key} </div>
    <div class="div_f"> no key here </div>
    <div class="div_g"> contains {key} </div>
  </div>
</div>
<div class="div_4"> no key here </div>
<div class="div_5"> no key here </div>
<div class="div_6"> contains {key} </div>
<div class="div_7"> no key here
  <div class="div_h"> no key here </div>
  <div class="div_i"> contains {key} </div>
  <div class="div_j"> no key here </div>
  <div class="div_k"> contains {key}
    <div class="div_l"> contains {key} </div>
    <div class="div_m"> no key here </div>
    <div class="div_n"> contains {key} </div>
  </div>
</div>
```

So the jQuery collection now contains the following DOM elements:

```
[".div_3", ".div_b", ".div_d", ".div_e", ".div_g", ".div_6", ".div_i", ".div_k", ".div_l", ".div_n"]

```

How can I filter this collection to become the following: ?

```
[".div_3", ".div_6", ".div_i", ".div_k"]

```

Thanks in advance guys for any help here !

---

@mplungjan - Long story:
The gist of it is that a collection of Regexs is used to collect all text nodes that contain a particular moustache style key for example "{{this\_is\_a\_key}}". Then "non-text-node" parents of these text nodes are added to a collection.

DOM elements in this jQuery collection (are converted into HTML strings and) need to be processed to replace the keys in PHP on the server via an AJAX request, however only the top-level elements need to be processed because children are already being processed within the top-level elements.