Brian K
Brian K

Reputation: 721

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!

Upvotes: 1

Views: 432

Answers (2)

charlietfl
charlietfl

Reputation: 171689

Following excludes the table and maps to array each element's text so you can separate each text block. If no whitespace in the elements then running text() on whole collection will leave no separation

var txt = $('#Explanation').parent().nextUntil('h2:has(#Transcript)').not('table').map(function() {
  return $(this).text()
}).get().join(' || ')

alert(txt)
<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>... don't select anything in this 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>

Used " || " delimiter in join() just to make it obvious where separator is...adjust accordingly

Upvotes: 1

Mohammad
Mohammad

Reputation: 21489

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>

Upvotes: 2

Related Questions