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>
This entry was posted in Web dev. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted May 5, 2011 at 5:58 pm | Permalink

    Not bad but this fails, for example, on the following:

    
    var elementNeeded = $('.firstElement').nextElementInDom('p,div');
    

    I had this requirement and the solution was as follows:

    
    var $foo = $('p,div');
    var idx = $foo.index('.firstElement');
    var next = $foo.eq( idx + 1 );
    

    Does that work for your case, too?

  2. Vladimirs
    Posted July 29, 2011 at 10:38 am | Permalink

    thanks a lot! very useful script

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

  • Categories

  • Archives