Reputation: 2743
I have a function like this:
var showTest = (condition) => {
if (condition === 'show') {
$('#id1').show();
$('#id2').show();
$('#id3').show();
}
else if (condition === 'hide') {
$('#id1').hide();
$('#id2').hide();
$('#id3').hide();
}
};
It works great. But if the argument 'condition' is always 'show' and 'hide', I feel that the if else is not needed as the function is just show() and hide()? So does jQuery allow me to do this and get rid of if else?
var showTest = (condition) => {
$('#id1').condition();
$('#id2').condition();
$('#id3').condition();
}
Upvotes: 0
Views: 73
Reputation: 617
If you want to map your condition to your element, you can try the code below as an example.
var conditionArray = [condition1, condition2, condition3];
var [conditionA, conditionB, conditionC] = conditionArray;
var showTest1 = $("#id1")[conditionA]();
var showTest2 = $("#id2")[conditionB]();
var showTest3 = $("#id3")[conditionC]();
This approach is using array destructuring which unpacked the items from the array and assign to a distinct variables.
Upvotes: 0
Reputation: 44087
Yes - use bracket notation like so:
var showTest = condition => {
$("#id1")[condition]();
$("#id2")[condition]();
$("#id3")[condition]();
};
And make it more concise using one call to $
:
var showTest = condition => {
$("#id1, #id2, #id3")[condition]();
};
Upvotes: 2