RubenGeert
RubenGeert

Reputation: 2952

jQuery addClass doesn't add class to element

I've the following html code

<ul class='selectul'>
    <li class='active'><a href='?sortby=views'>by Popularity.</a></li>
    <li><a href='?sortby=recency'>by Recency.</a></li>
    <li><a href='?sortby=alphabet'>Alphabetically.</a></li>
</ul>

When any <li> element is clicked, I want to add class='active' to it. None of its siblings is then allowed to have this class. I tried to do this with the following jQuery code

(function(){
    $('.selectul li').on('click',function(){
        $(this).addClass('active');
        $(this).siblings().removeClass('active');
    });
}())

but it doesn't seem to do anything. I'm just getting started with jQuery so I apologize if this question is rather basic.

Upvotes: 1

Views: 1651

Answers (4)

PaulRoth
PaulRoth

Reputation: 314

The script is all right. The problem is somewhere else. Once you click the link, the document reload and you do not notice the change of classes.

Try:

(function(){
  $('.selectul li').on('click',function(){
    $(this).addClass('active');
    $(this).siblings().removeClass('active');
    return false;
  });
}());

return false interrupts the Click-Event and prevent the reload of the document.

Upvotes: 5

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

I think you should code like this

http://jsfiddle.net/3WBvL/2/

$(document).ready(function(){
    $('.selectul li').on('click',function(){

        $(this).addClass('active');
        $(this).siblings().removeClass('active');
    });
});

Upvotes: 0

David Houde
David Houde

Reputation: 4778

Your code looks good, and I have verified it working @ jsfiddle.net

http://jsfiddle.net/kEfyT/1/

$(document).ready(function(){
    $('.selectul li').on('click',function(){
        $(this).addClass('active');
        $(this).siblings().removeClass('active');
    });
});

Upvotes: 1

Stephen Binns
Stephen Binns

Reputation: 765

Try waiting for a document ready event as the elements might not be on the page yet.

$(function(){
    $('.selectul li').on('click',function(){
        $(this).addClass('active');
        $(this).siblings().removeClass('active');
    });
});

Upvotes: 0

Related Questions