I was wondering if there is any way to rewrite the
for loop using
What if I say you can avoid
for loop completely.
Yes, you can avoid loop by letting jQuery do that for you. jQuery accepts multiple comma-separated selectors and internally iterate over each selector and perform operations.
generators is an array of elements, this array elements can be joined with
, as glue, to create the selector.
Let's say, we have an array
var selectors = ['#someId', '.myClass', 'tag'] and we want to add a class to all these selectors. We can iterate over the array and add the class to each element individually or we can combine the array elements somehow to create a comma-separated string and pass this to
jQuery as selector.
selectors.join(', ') will join the array elements by
,, thus giving
'#someId, .myClass, tag' which is valid selector and can be passed to
jQuery and any method defined on
jQuery prototype can be called on it.
Same logic can be used, in your case.
join will add the glue between the elements of array, the prefix and suffix need to be concatenated.
The selector can be created using
+ list.join('"], .generatorContainer[data-generator="')
Line #1 is the prefix
Line #2 will give
firstElement"], .generatorContainer[data-generator="secondElement"], ..., .generatorContainer[data-generator="lastElement
Line #3 will add suffix to make the selector valid.
With this, the code will be
var selector = '.generatorContainer[data-generator="' + list.join('"], .generatorContainer[data-generator="') + '"]';
$(selector).doMagic(); // He He
To add to the complexity,
not() can be used to exclude elements
$('.generatorContainer').not(selector).hide(); // Hide those except in array
$(selector).show(); // Show only those in array