I am currently wondering the following: I have two arrays:
const highlightClasses = ['highlightPlace', 'highlightOrg', 'highlightName'];
const elements =['place', 'org', 'name']
and a "toggleClass-function" which does magically toggle classes:
const toggle = (element, className) => $(element).toggleClass(className);
elements contains all elements that I want to toggle the class from highlightClasses.
my current solution is this:
const highlightEntities=() => {
toggle($('place'), 'highlightedPlace');
toggle($('org'), 'highlightedOrg');
toggle($('name'), 'highligtedName');
}
I was thinking about sth like a
for each (element in elements){
do magic
}
I want for elements[0] the highlightClasses[0] to be toggled and so on. (in this case) Besides, it is only these three elements and classes, I do not know whether it actually is worth the time, but in case I have to expand it, I'd like to know a more elegant way
is there such a way?
Try something like this:
for (let i = 0; i < elements.length; i++) {
toggle($(elements[i]), highlightClasses[i]);
}
Also I would recommend a data structure like this:
const elements = [
{ name: 'place', highlightClass: 'highlightPlace' },
{ name: 'org', highlightClass: 'highlightOrg' },
{ name: 'name', highlightClass: 'highlightName' }
]
The more simple for-in loop would accordingly be:
for (const element in elements) {
toggle($(element.name), element.highlightClass);
}
This way you won't run into errors when your Arrays have different lengths.