Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery prevAll displaying text in backward ordering

Tags:

html

jquery

find

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

like image 533
SoulieBaby Avatar asked Jun 06 '10 22:06

SoulieBaby


2 Answers

Dunno if following will work:

Array.prototype.reverse.call($(".content").find("h2:first").prevAll()); 
like image 76
azatoth Avatar answered Sep 24 '22 15:09

azatoth


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() )

like image 40
Reza Mamun Avatar answered Sep 26 '22 15:09

Reza Mamun