Imagine the following HTML
<div id="outer">
<div id="elem1"></div>
<div class="helperBtn"></div>
<div class="helperBtn"></div>
<div id="elem2"></div>
<div class="helperBtn"></div>
<div class="helperBtn"></div>
<div id="elem3"></div>
<div class="helperBtn"></div>
<div class="helperBtn"></div>
</div>
How does one select elem2 and both following div.helperBtn's ?
I've tried something like this: $('#elem2').add(':next') but couldn't get any working solution.
Any ideas?
In your case, you can use nextUntil() with addBack():
var elements = $("#elem2").nextUntil("#elem3").addBack();
The above will match all the elements between #elem2 and #elem3, then add #elem2 back into the set. The resulting jQuery object will contain three elements.
EDIT: I see legitimate concern in another answer about this solution being hardcoded. That's true, but it can easily be modified so you only have to specify the first element:
var elements = $("#elem2").nextUntil(":not(.helperBtn)").addBack();
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