Ra.
Ra.

Reputation: 955

Traversing backwards using jquery

I have a code like below

If I click the "finallink" class, i want to select or display all previous elements that matches "level_" class until the "parent" class. There are so many "level" classes like "level_1, level_2... level_n.

<div class="parent">
    <a href="#" class="level_0">level 0 text</a>

    <div class="someclass">1</div>
    <div class="someclass">2</div>
    <div class="someclass">3</div>
    <div class="someclass">4</div>

    <h1 class="level_1">level 1 text</h1>

    <div class="someclass">1</div>
    <div class="someclass">2</div>
    <div class="someclass">3</div>
    <div class="someclass">4</div>

    <h2 class="level_2">level 2 text</h2>

    <a href="#" class="finallink">link</a>
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

I tried something like this

$(".finallink").closest("h3").prevAll("level_1").css("background-color","yellow");

How Do I get all "level_" values. Example code jsfiddle

Upvotes: 2

Views: 1503

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074158

You've said the "previous" levels, by which I mean the ones prior to the link. You've said "until the parent class" and as that's the container, that means we can use all previous siblings and then filter to just the ones with one of the level_x classes:

$(".finallink").click(function() {
    var list = $(this).prevAll().filter(function() {
        return this.className.match(/\blevel_/);
    });

    // Use `list`
});

Live Example | Source

This works even if you end up with other classes in front of level_1, e.g. <h2 class="something level_1" ...>.

Upvotes: 0

adeneo
adeneo

Reputation: 318182

If the markup is like the question, where the finallink is the last element, or at least does'nt have any elements with a _level class below it within the same parent, you could first get the closest parent matching the .parent class, then find() all elements that matches the _level class:

$(".finallink").closest(".parent")
               .find("[class^='level_']")
               .css("background-color","yellow");

Otherwise, you could do:

$(".finallink").prevAll()
               .filter("[class^='level_']")
               .css("background-color","yellow");​

Upvotes: 3

Related Questions