Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for class using if, then add class jquery

Tags:

jquery

I'm new to jquery and has some problems with the following code, the code is trying to replace the class of an item when clicked, the first part works as expected. If the item has a class of none it adds featSelected, however if i then click again to deselect it, it does not add the class of none. Any ideas would be appreciated, be gentle as i am in the throws of learning jquery(from book, looking at some courses though!).

 <script type="text/javascript">
          $('li span[id^="feat"]').click(function(){
          if ($(this).hasClass('none')) {
              $(this).addClass("featSelected") 
            }

            else if ($(this).hasClass('featSelected')) {
              $(this).addClass("none") 
            }

    })

    </script>

Any help would be appreciated.

Jason

like image 224
Jason Congerton Avatar asked Dec 13 '25 23:12

Jason Congerton


1 Answers

Use the built-in toggleClass() function:

$('li span[id^="feat"]').click(function(){
    $(this).toggleClass("none featSelected");
});

Working demo: http://jsfiddle.net/7fBLH/

Alternatively, you might want to consider not using none as a class name, since it sounds like you're using it to semantically say "This element has no class". If that's the case, you should use default styling and CSS cascading:

li span[id^="feat"] { 
    /* default styles here */
}
.featSelected {
    /* these styles show when the element has this class name */
}
like image 134
Andy E Avatar answered Dec 15 '25 23:12

Andy E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!