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?
You want nextAll
:
jQuery(yourTextarea).nextAll('.select_this:first');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With