Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jQuery, how do I select elements between elements with certain classes?

Tags:

jquery

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.

like image 918
dangerChihuahua007 Avatar asked May 14 '12 20:05

dangerChihuahua007


4 Answers

$('li.foo').nextUntil('li.bar')

http://jsfiddle.net/zZRDB/1/

like image 65
dotjoe Avatar answered Oct 22 '22 10:10

dotjoe


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;
},​
like image 38
gdoron is supporting Monica Avatar answered Oct 22 '22 08:10

gdoron is supporting Monica


Try,

 $('li.bar').prevUntil('.foo')

DEMO

like image 38
Selvakumar Arumugam Avatar answered Oct 22 '22 10:10

Selvakumar Arumugam


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');

like image 33
The System Restart Avatar answered Oct 22 '22 10:10

The System Restart