The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Question about jQuery .hasClass()

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #151629

    Is there is a more efficient way to write $(this).hasClass('myclass') inside a click function? Below is a reference to the code in question , including a working sample…Any help is appreciated. Thank you.

    $('.button').click(function () {
        if ($(this).hasClass('red')) {
            alert('Red Works');
        } else if ($(this).hasClass('blue')) {
            alert('Blue Works');
        } else if ($(this).hasClass('green')) {
            alert('Green Works');

    Working Sample:


    Really difficult to say without fully knowing what the code is trying to accomplish.

    For starters, I’d be storing $(this) as a variable just inside the click function like this:

    var button = $(this);

    …and then going:


    Depending on what you’re trying to do you might want to look into using a switch:

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.