I have the code below to perform operations on the classList of every DOM-Element in the given list.
function editClassListOfElements(elements, className, operation) {
switch (operation) {
case "add":
[].forEach.call(elements, function (element) {element.classList.add(className)});
break;
case "remove":
[].forEach.call(elements, function (element) {element.classList.remove(className)});
break;
case "toggle":
[].forEach.call(elements, function (element) {element.classList.toggle(className)});
break;
default:
break;
}
}
and I want to change it to something like this:
function editClassListOfElements(elements, className, operation) {
[].forEach.call(elements, function (element) {element.classList. + operation + (className)});
}
If this is possible, how is it done?
-
Possible duplicate of Using a variable for a key in a JavaScript object literalTeemu– Teemu2016年09月12日 07:39:04 +00:00Commented Sep 12, 2016 at 7:39
1 Answer 1
You can access fields of an object with brackets.
element.classList.add is equivalent to element.classList["add"]. So you can just do element.classList[operation](className) and it will call the function of classList named like the value of variable operation.
answered Sep 12, 2016 at 7:35
Philipp
70.2k10 gold badges121 silver badges159 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js