Solution 1 :

We do need to handle the parents

const $from = $("tr").has(".separator1");
const $to   = $("tr").has(".separator2");
const $range = $from.nextUntil($to)
console.log($range.text())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>
        <div class="separator1">Sep1</div>
      </td>
    </tr>
    <tr><td>Cell 1</td></tr>
    <tr><td>Cell 2</td></tr>
    <tr><td>Cell 3</td></tr>
    <tr>
      <td>
        <div class="separator2">Sep2</div>
      </td>
    </tr>
  </tbody>
</table>

Problem :

I have the following element-tree in the DOM:

<table>
  <tbody>
    <tr>
      <td>
        <div class="separator1"></div>
      </td>
    </tr>
    <tr></tr>
    <tr></tr>
    <tr>
      <td>
        <div class="separator2"></div>
      </td>
    </tr>
  </tbody>
</table>

I also have the following structure:

<div class="separator1"></div>
<div></div>
<div></div>
<div class="separator2"></div>

How do I get all elements that are between the element with class “separator1” and the element with class “separator2” in both scenarios?

In the first example I want to return all tr’s that are between in the second example all divs that are between but with the same function.

What I tried were nextAll() and nextUntil() but they are only returning siblings which is working in the case of the second example but not with the first one.

Comments

Comment posted by mplungjan

Why are we not allowed to target the parents?

Comment posted by JakkSwords

There are two different cases which i would like to handle global and i dont want to target the parents because in the second case there are different parents(so no tr-parents but div-parents) than in case 1.

Comment posted by freedomn-m

Clarified the question by reording from “I have A, how do I do X (also for B)” to “I have A and B, how do I do X (for both)”

Comment posted by freedomn-m

Short answer: you can’t. You’re thinking in “flat text html file”, but that’s now how DOM elements are arranged, they’re in a tree format and in the first case there are no other elements around

Comment posted by JakkSwords

Thanks for the replies. I just added a new class to the parents manually, so i can work with nextUntil().

By

Leave a Reply

Your email address will not be published. Required fields are marked *