Skip to content Skip to sidebar Skip to footer

Jquery Adding A Class

I want add a class when a
  • element clicked. but it didn't work. Here's JQuery snippet $('.mama').click(function(){ var arr = ['cat','dog', 'mice', 'bird'];
  • Solution 1:

    This should work:

    $(".mama").click(function(){   
        var $this = $(this);     
        var arr = ["cat","dog", "mice", "bird"];
        alink =  $(this).text();        
    
        $.each(arr, function(index, value) {
            if(alink == value){
                $this.addClass('hi'); 
            }
        }); 
    });
    

    because this inside the each is not the DOM element <li>.

    Solution 2:

    You probably just need to do this:

    http://jsfiddle.net/reugB/1/

    $('.mama').on('click', function(evt) {
        evt.preventDefault();
        $(this).addClass('hi');
    });
    

    Solution 3:

    Use this to refer to current element which was clicked.

    $(".mama").click(function (e) {
        e.preventDefault();
        $(this).addClass('hi');
    });
    

    Solution 4:

    If you mean add the class hi to the clicked li, just do like below:

    $(".mama").click(function(e){
        e.preventDefault();
        $(".mama").removeClass('hi');
        $(this).addClass('hi')        
    });
    

    Solution 5:

    .hi { background-color: #f00!important;}
    
    
     $('.mama').on('click', function(evt) {
    evt.preventDefault();
    $(this).addClass('hi');
    

    });

    Post a Comment for "Jquery Adding A Class"