I need to assemble an array of nodes that are between two label elements that are in different parents. Suppose I need paragraphs.

<p>ΠŸΠ΅Ρ€Π²Ρ‹ΠΉ <span class="before"></span>ΠΏΠ°Ρ€Π°Π³Ρ€Π°Ρ„ с ΠΊΠ°ΠΊΠΈΠΌ-Ρ‚ΠΎ тСкстом</p> <p>Π’Ρ‚ΠΎΡ€ΠΎΠΉ ΠΏΠ°Ρ€Π°Π³Ρ€Π°Ρ„ с ΠΊΠ°ΠΊΠΈΠΌ-Ρ‚ΠΎ тСкстом</p> <p>Π’Ρ€Π΅Ρ‚ΠΈΠΉ ΠΏΠ°Ρ€Π°Π³Ρ€Π°Ρ„ с ΠΊΠ°ΠΊΠΈΠΌ Ρ‚ΠΎ тСкстом</p> <p>Π§Π΅Ρ‚Π²Π΅Ρ€Ρ‚Ρ‹ΠΉ ΠΏΠ°Ρ€Π°Π³Ρ€Π°Ρ„ <span class="after"></span> с ΠΊΠ°ΠΊΠΈΠΌ-Ρ‚ΠΎ тСкстом</p> 

As a result, I need to get an array from the second and third paragraphs. If the element is not completely between the labels - it is excluded. nextUntil from nextUntil did not help - the label nodes with such a dislocation stupidly do not see the content among themselves.

    1 answer 1

    Alternatively, you can try the following construction:

     function findNodesBetweenElements(selector, startNode, endNode) { let paragraphs = Array.from(document.querySelectorAll(selector)); let range = document.createRange(); range.setStartAfter(startNode); range.setEndBefore(endNode); let result = paragraphs.filter((item) => { return range.intersectsNode(item) }); return result } let p = Array.from(document.querySelectorAll('p')); result = findNodesBetweenElements('p', p[0], p[p.length - 1]); console.log(result); 
     <p>ΠŸΠ΅Ρ€Π²Ρ‹ΠΉ <span class="before"></span> ΠΏΠ°Ρ€Π°Π³Ρ€Π°Ρ„ с ΠΊΠ°ΠΊΠΈΠΌ-Ρ‚ΠΎ тСкстом</p> <p>Π’Ρ‚ΠΎΡ€ΠΎΠΉ ΠΏΠ°Ρ€Π°Π³Ρ€Π°Ρ„ с ΠΊΠ°ΠΊΠΈΠΌ-Ρ‚ΠΎ тСкстом</p> <p>Π’Ρ€Π΅Ρ‚ΠΈΠΉ ΠΏΠ°Ρ€Π°Π³Ρ€Π°Ρ„ с ΠΊΠ°ΠΊΠΈΠΌ Ρ‚ΠΎ тСкстом</p> <p>Π§Π΅Ρ‚Π²Π΅Ρ€Ρ‚Ρ‹ΠΉ ΠΏΠ°Ρ€Π°Π³Ρ€Π°Ρ„ <span class="after"></span> с ΠΊΠ°ΠΊΠΈΠΌ-Ρ‚ΠΎ тСкстом</p> 

    The function takes a selector and two nodes into the sss parameters, between which the search takes place, for example, I added the first and last paragraph, if you wish, you can throw any nodes there. But, for example, if the desired node lies inside the excluded one, then it will be included in the result.

    • Sergey, thank you, an interesting decision. Let's experiment with the flexibility thereof - Ilya Bazhinov