Jquery prev

I am trying to use jQuery to get all paragraphs up to the first h2 tag in my content. Here is the code I'm using:

$(".content").find("h2:first").prevAll().text() 

Which captures the content, although it displays it in the reverse order. Content example:

 <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 outputs:

 <p>paragraph 3</p> <p>paragraph 2</p> <p>paragraph 1</p> 

Is there a way to reverse this, so is it in the correct order? I tried using nextAll using different codes, but it looks like it captured all my content or didn't work at all lol

+4
source share
2 answers

The following actions cannot be performed:

 Array.prototype.reverse.call($(".content").find("h2:first").prevAll()); 
+7
source

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 an array of jQuery array using $( ... ) as above; For example: $( [].reverse() )

+2
source

Source: https://habr.com/ru/post/1312031/


All Articles