I'm trying to use jQuery to get all the paragraphs before the first h2 tag in my content. Here's the code I'm using:
$(".content").find("h2:first").prevAll().text()
Which is grabbing the content, although it's displaying it in backwards order. Example content:
<div class="content">
<p>paragraph 1</p>
<p>paragraph 2</p>
<p>paragraph 3</p>
<h2>First h2 tag</h2>
<p>paragraph 4</p>
<p>paragraph 5</p>
<p>paragraph 6</p>
<h2>Second h2 tag</h2>
</div>
The above code is outputting:
<p>paragraph 3</p>
<p>paragraph 2</p>
<p>paragraph 1</p>
Is there any way of reversing this, so it's in the correct order? I have tried using nextAll using different codes, but it seems to grab all of my content, or not work at all lol
Dunno if following will work:
Array.prototype.reverse.call($(".content").find("h2:first").prevAll());
We can just do this:
$( $(".content h2:first").prevAll().get().reverse() ).text();
Note: [].reverse()
is a javascript array (here with DOM elements) and you need to make it a jQuery array wrapping with $( ... )
like above; For example: $( [].reverse() )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With