3

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?

SU3
  • 5,064
  • 3
  • 35
  • 66
  • 3
    `node[condition ? 'addClass' : 'removeClass']('myclass');` worked fine for me... What is node exactly? I tested it with `$("body")[(1===1) ? "addClass" : "removeClass"]("b")` – epascarello Mar 08 '19 at 04:17
  • 2
    But seems like you are just reinventing toggleClass `node.toggleClass("foo", condition)` – epascarello Mar 08 '19 at 04:19
  • @epascarello Thanks! Didn't know that function existed. – SU3 Mar 08 '19 at 04:20

3 Answers3

1

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.

SU3
  • 5,064
  • 3
  • 35
  • 66
0

Can be toggled with vanilla java script

node.classList.toggle('myclass',condition);
Murali Nepalli
  • 1,588
  • 8
  • 17
0

You can do this by assigning the function to a variable.

var twoLevel = {
  "foo" : {
    log: console.log
  },
  "bar" : {
    log: window.alert
  }
}

var fn = true ? twoLevel["foo"].log : twoLevel["bar"].log;
fn('test')
Steven Stark
  • 1,249
  • 11
  • 19