Alex N
Alex N

Reputation: 1121

How change class for all elements after and before this element?

Good day.

I have code html:

<span class="empty-star level" style="cursor:pointer" id="1"></span>
<span class="empty-star level" style="cursor:pointer" id="2"></span>
<span class="empty-star level" style="cursor:pointer" id="3"></span>
<span class="empty-star level" style="cursor:pointer" id="4"></span>
<span class="empty-star level" style="cursor:pointer" id="5"></span>

I would like that when i click on element with class level all elements before him, change class with empty-class to good-class and all elements after him change class with good-class to empty-class.

Tell me please how make this?

Upvotes: 1

Views: 555

Answers (5)

Frank van Wijk
Frank van Wijk

Reputation: 3252

$('.level').on('click', function() {
    $(this).prevAll('.empty-class').removeClass('empty-class').
        addClass('good-class');
    $(this).nextAll('.good-class').removeClass('good-class').
        addClass('empty-class');
});

Upvotes: 2

Siddharth Nagar
Siddharth Nagar

Reputation: 412

$(".level").click(function()
{
    $(this).prevAll().removeClass("empty-class").addClass("good-class");
    $(this).nextAll().removeClass("good-class").addClass("empty-class");
});

Upvotes: 0

SG 86
SG 86

Reputation: 7078

You can use the .prev() and .next() jQuery functions!

http://api.jquery.com/prev/

http://api.jquery.com/next/

And you can use .addClass() and .removeClass()

http://api.jquery.com/addClass/

http://api.jquery.com/removeClass/

//Edit:

If you want to asign classes to more then one prev or next element you can use .prevAll() / .nextAll() or .prevUntil() / .nextUntil()

http://api.jquery.com/prevAll/

http://api.jquery.com/nextAll/

http://api.jquery.com/prevUntil/

http://api.jquery.com/nextUntil/

Upvotes: 0

mridula
mridula

Reputation: 3281

You can try this:

$(".level").click(function() {
    var thisId = $(this).attr("id");
    $.each($(".level"), function(index) {
        if(this.id < thisId) {
            $(this).removeClass("empty-class");
            $(this).addClass("good-class");
        }
        else if(this.id > thisId) {
            $(this).removeClass("good-class");
            $(this).addClass("empty-class");
        }
    });
});

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173562

You can use .prevAll() and nextAll() for this purpose:

$('.level').on('click', function() {
    $(this)
      .prevAll('.empty-class')
        .toggleClass('empty-class good-class') // remove empty, add good
        .end()
      .nextAll('.good-class')
        .toggleClass('good-class empty-class'); // remove good, add empty
});

Upvotes: 4

Related Questions