Kyle
Kyle

Reputation: 293

.not method fails?

I have written two jQuery functions, the simplified version of which run thus:

$('button.class').not('.selected').on('click', function() {
    console.log('not selected');
    console.log($(this));
    $(this).addClass('selected');
}

$('button.class.selected').on('click', function() {
     console.log('selected');
     console.log($(this));
     $(this).removeClass('selected');
}

Clicking on the button always logs the following in the console:

not selected
[<button class="someClass1 someClass2 selected">Text</button>]

The Web Inspector shows this before clicking on the button:

<button class="someClass1 someClass2">Text</button>

and this after clicking on it:

<button class="someClass1 someClass2 selected">Text</button>

Clicking on it again changes nothing.

Switching addClass() to toggleClass() succeeds in toggling 'selected' on and off, but still always logs not selected, which suggests something is going on with my selectors. Why is the first function always being called even when 'selected' is clearly one of the classes associated with the button element?

I noticed in testing some solutions that hard-coding 'selected' as a class of button results in the opposite problem: only second of the functions is ever called, even though toggleClass() works as intended. Do classes added via jQuery not "count" as classes?

Upvotes: 0

Views: 48

Answers (2)

Ilia G
Ilia G

Reputation: 10211

The CSS selector is evaluated at the time you run it. I wouldn't expect that there are any elements matching $('button.class.selected') on page load, so your second handler is never executed, because it is never bound to anything. What you should be doing is attaching event to some base selector such as $('button.class') and then doing filtering when event is fired.

$("button.class").on("click", function()
{
    if ($(this).is(".selected"))
    {
        console.log('selected');
        console.log($(this));
        $(this).removeClass('selected');
    }
    else
    {
        console.log('not selected');
        console.log($(this));
        $(this).addClass('selected');
    }
});

Either version works, but one might be more appropriate than the other, depending on what are you actually trying to do.

If all you are looking to do is to add/remove .selected on button click then this much simpler version will do the job

$("button.class").on("click", function() { $(this).toggleClass("selected"); });

Upvotes: 3

qwertymk
qwertymk

Reputation: 35256

Try changing :

$('button.class').not('.selected')

To:

$('button').not('.selected')

And :

$('button.class.selected')

To:

$('button.selected')

Upvotes: 0

Related Questions