How can I get the elements between 2 other elements?
Like if I had:
<div class="c1"></div>
<div class="c2"></div>
<div class="c3"></div>
<div class="c4"></div>
<div class="c5"></div>
<div class="c6"></div>
<div class="c7"></div>
I want to get the elements between div.c3
and div.c6
.
A sibling is an element that shares the same parent with another element. In the diagram below, the <li>'s are siblings as they all share the same parent - the <ul>.
The ("element ~ siblings") selector selects sibling elements that appear after the specified "element".
jQuery siblings() Method Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward and backwards along siblings of DOM elements. Tip: Use the prev() or next() method to narrow down the search for only previous or next sibling elements.
With nextUntil
[docs]:
var $siblings = $('.c3').nextUntil('.c6');
You might want to first check if elements come in the proper order, othenwise nextUntil will return unexpected set of elements.
/**
* Returns an array of sibling elements between `from` and `to` including `from` and `to`
*/
function getElementsInBetween (from, to) {
var range = [];
if (from.index() > to.index()) { //ensure that 'from' is before 'to'
from = [to, to = from][0]; //swapping from and to
}
if (from.is(to)) {
range = [from];
} else {
range = from.nextUntil(to).add(from).add(to);
range = $.makeArray(range);
}
return range;
};
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