I have an unordered list.
<ul>
<li class="foo">Baz</li>
<li>Select Me!</li>
<li>Select Me!</li>
<li>Select Me!</li>
<li class="bar">Baz</li>
<li>Don't Select Me</li>
<li>Red Herring List Item</li>
</ul>
How do I select the list items in between the list items with classes foo and bar using jQuery? I do not know the contents of any list items. I also do not know how many list items are there to be selected so I cannot depend on a count.
$('li.foo').nextUntil('li.bar')
http://jsfiddle.net/zZRDB/1/
var $elements = $('.bar').prevUntil('.foo');
Or the other way:
var $elements = $('.foo').nextUntil('.bar');
Demo
If you're intersted to know how it's implemented, check out the source code:
nextUntil: function(elem, i, until) {
return jQuery.dir(elem, "nextSibling", until);
},
prevUntil: function(elem, i, until) {
return jQuery.dir(elem, "previousSibling", until);
},
dir: function(elem, dir, until) {
var matched = [],
cur = elem[dir];
while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery(cur).is(until))) {
if (cur.nodeType === 1) {
matched.push(cur);
}
cur = cur[dir];
}
return matched;
},
Try,
$('li.bar').prevUntil('.foo')
DEMO
var index1 = $('li.foo').index(),
index2 = $('li.bar').index()-1;
$('li:gt('+ index1+'):lt('+ index2+')', 'ul');
or $('li.foo').nextUntil('li.bar');
or $('li.bar').prevUntil('li.foo');
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