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> |
Warning: Declaration of Social_Walker_Comment::start_lvl(&$output, $depth, $args) should be compatible with Walker_Comment::start_lvl(&$output, $depth = 0, $args = Array) in /home/customer/www/arronwoods.com/public_html/blog/wp-content/plugins/social/lib/social/walker/comment.php on line 18
Warning: Declaration of Social_Walker_Comment::end_lvl(&$output, $depth, $args) should be compatible with Walker_Comment::end_lvl(&$output, $depth = 0, $args = Array) in /home/customer/www/arronwoods.com/public_html/blog/wp-content/plugins/social/lib/social/walker/comment.php on line 42
Not bad but this fails, for example, on the following:
I had this requirement and the solution was as follows:
Does that work for your case, too?
thanks a lot! very useful script
Thank you! That’s exactly what I need!
Brilliant! Exactly what I needed.
Thank you very much. Very helpful indeed.