The following snippet works
if (condition)
node.addClass('myclass');
else
node.removeClass('myclass');
but not this one
node[condition ? 'addClass' : 'removeClass']('myclass');
nor this one
(condition ? node.addClass : node.removeClass)('myclass');
If I test it with
console.log(node[condition ? 'addClass' : 'removeClass']);
the browser prints that it's a function. Why can't I call it?
It apparently works the way I gave my examples here. It doesn't work with one extra level of indirection.
function print(x) {
console.log(x);
return x;
}
print(condition ? node.addClass : node.removeClass)('myclass');
With this code, Chrome tells me this:
Uncaught TypeError: Cannot read property '0' of undefined
But I found out I can circumvent the problem by using call to pass the node as this to the function.
print(condition ? node.addClass : node.removeClass).call(node,'myclass');
Obviously, the right solution in this specific case is to use toggleClass, as @epascarello pointed out. I'm a little surprised that this gets lost in this scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With