jQuery find next element in DOM by selector

If you need to find the next occurrence of an element within the DOM, but aren’t sure where it is (i.e. you can’t just use $.next) I wrote a jQuery plugin that will traverse through the DOM from the current element til it hits either the ‘body’ tag or a parent you specify.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(function( $ ){
    $.fn.nextElementInDom = function(selector, options) {
        var defaults = { stopAt : 'body' };
        options = $.extend(defaults, options);
 
        var parent = $(this).parent();
        var found = parent.find(selector);
 
        switch(true){
            case (found.length > 0):
                return found;
            case (parent.length === 0 || parent.is(options.stopAt)):
                return $([]);
            default:
                return parent.nextElementInDom(selector);
        }
    };
})( jQuery );

Download it here: jquery.nextElementInDom.js

And here is how you would use it:

1
var elementNeeded = $('.firstElement').nextElementInDom('.secondElement');

Where your HTML might look like this:

<html>
  <body>
    <div>
      <span class="firstElement">Our first element</span>
    </div>
 
    <ul>
      <li>
        <span class="secondElement">Second element is in a different place</span>
      </li>
    </ul>
  </body>
</html>