tags:

views:

39

answers:

1

hi all, 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

+2  A: 

Dunno if following will work:

Array.prototype.reverse.call($(".content").find("h2:first").prevAll()); 
azatoth
don't forget the .text() at the end (outside of the reverse call). You have to do this instead of just calling reverse() because the jquery result object doesn't keep all the native javascript array methods.
colinmarc