Brian K Brian K - 1 month ago 11
HTML Question

How to select elements between two "h2" except one element using jquery?

so I'm working with a website that is designed like this:

<h2>
<span id="Explanation"> Explanation </span>
</h2>
<table> ... don't select anything in this table </table>
<a href="https://www.google.com/">hey</a>
<p> What's up? </p>
<p> How's life? </p>
<h2>
<span id="Transcript"> Transcript </span>
</h2>
<p> Don't select this </p>


I want to select everything in between the explanation header and the transcript header using jQuery, but I'm having trouble getting any text at all. My current jQuery to get this is as follows:

explanation = "";
explanation = $("h2 #Explanation").nextUntil("h2 #Transcript").text();


But right now, I don't select any text at all. Also, I'm not sure about how to get only the a and p text and not the table text. Any help you guys could give me would be much appreciated, thanks!

Answer

You need to use :has() selector to select h2 has specific child and use .not() to remove specific element from set of selector.

$("h2:has(#Explanation)").nextUntil("h2:has(#Transcript)").not("table").text();

var explanation = $("h2:has(#Explanation)").nextUntil("h2:has(#Transcript)").not("table").text();
console.log(explanation);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>
  <span id="Explanation"> Explanation </span>
</h2>
<table><tr><td>table</td></tr></table>
<a href="https://www.google.com/">hey</a>
<p> What's up? </p>
<p> How's life? </p>
<h2>
  <span id="Transcript"> Transcript </span>
</h2>
<p> Don't select this </p>