Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add next item and item after next to current collection

Tags:

jquery

dom

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?

like image 923
peipst9lker Avatar asked Dec 22 '25 05:12

peipst9lker


1 Answers

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();
like image 82
Frédéric Hamidi Avatar answered Dec 23 '25 18:12

Frédéric Hamidi