Hooray Im Helping
Hooray Im Helping

Reputation: 5264

Using jQuery, how do I find all instances of a class that appear between another class

For example:

<table>
  <tr class="highlight" id="click">
    <td>Rusty</td>
  </tr>
  <tr class="indent">
    <td>Dean</td>
  </tr>
  <tr class="indent">
    <td>Hank</td>
  </tr>
  <tr class="highlight">
    <td>Myra</td>
  </tr>
</table>

Say when I click on the hr with the id click how would I find all instances of class indent until the next instance of class highlight?

Upvotes: 1

Views: 3074

Answers (2)

Wil
Wil

Reputation: 847

This applies the click only to the highlight with "click" and returns only the indents between "click" and the next highlight it encounters.

It uses the jQuery ~ "next siblings" selector to do a little more of the work for you.

http://jsfiddle.net/w_barath/bFZnH/2/

$("#click").bind('click', function() {
    var good = true;
    $("#click ~ tr").each(function(e) {
        if (this.className == "highlight") {
            good = false;
        }
        if (good && this.className == "indent") {
            this.style.background="red";
        }
    });
});

Upvotes: 1

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124878

$('tr.highlight').click(function() {
    var $indents = $(this).nextAll('tr.indent');
});

EDIT

That's seems to select all .indents regardless of .highlights. Try this:

$('tr.highlight').click(function() {
    var row = $(this).next();
    var selection = false;
    while(row.hasClass('indent')) {
        if(!selection) {
            selection = row;
        } else {
            selection.add(row);
        }
        row = row.next();
    }
});

Upvotes: 7

Related Questions