Get previous or next HTML element with a certain class

If you want to get the previous or next element with a certain class you can use JQuery and a CSS selector. This may be useful in certain circumstances, I found myself in that position today and thought I’d share it here.


An example markup.

<div class="AnElementYouWant">Some beginning text</div>
<div id="ElementAfter">More text</div>
<div class="AnElementYouWant">Some ending text</div>


Given the above markup we can use this Javascript to select the divs around the centre div.

var first = $(this).prevAll("AnElementYouWant:first");
var last = $(this).nextAll("AnElementYouWant:first");

So console.log(first.text()) would output “Some beginning text” and console.log(last.text()) would output “Some ending text”.

Hope someone finds that useful.

Leave a Reply

Your email address will not be published. Required fields are marked *