Ternary Operator for more than 2 conditions

var testCond = $('body').hasClass('theme-a') ? 'a' : 'b';

Need to include new theme class name into the body like mentioned above. But, getting javascript error.

Not sure is there any easy method to solve this. Can add condition like below?

var testCond = $('body').hasClass('theme-a') ? 'a' : 'b' : 'c';

2 Answers

$(‘body’).hasClass(‘theme-a’) ? ‘a’ : $(‘body’).hasClass(‘theme-b’) ? ‘b’ : ‘c’;

A lookup table is flexible:

var class_lookup = { 'theme-a' : 'a', 'theme-b' : 'b', 'theme-c' : 'c', /* ... */ };
var testCondList = $('body').attr('class').split(' ').map(c => class_lookup[c]).filter(x => x);

This will create an array of all the values in the lookup table that has a key in the class list.

Archive from: https://stackoverflow.com/questions/59043229/ternary-operator-for-more-than-2-conditions

Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *