Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector for finding the first element after a given element that matches a selector

Let's say I have this HTML:

 <textarea>blah</textarea>
 <br>
 <div class="select_this">hello!</div>

How can I select the DIV with class "select_this" when I already have the textarea identified? I don't want to use a class selector on the entire document because I'm working with a large document and class lookups are slow in older browsers.

jQuery .next() doesn't seem to do the trick, closest() only looks up the DOM tree, and .nextUntil() qualifies on everything I need except for the "select_this" div. Any other options out there?

like image 725
Elliot B. Avatar asked May 22 '12 17:05

Elliot B.


2 Answers

You want nextAll:

jQuery(yourTextarea).nextAll('.select_this:first');
like image 26
James Avatar answered Oct 04 '22 22:10

James


There are two ways to do it.

Use this if you only have a few siblings:

$('textarea').nextAll('div.select_this').first();

The downside of this is that it test every subsequent element to see if it matches the selector, even after it's found the first one. Use this if you have many, many siblings, to save on evaluation:

$('textarea').nextUntil('div.select_this').andSelf().last().next();

Note also that it's better to use the first and last methods, rather than their corresponding selectors (:first, :last), because browsers don't natively understand the selectors, which slows the expression down considerably.

Edited to incorporate andSelf per comment below.

like image 61
lonesomeday Avatar answered Oct 04 '22 20:10

lonesomeday