I want to loop through the array,
jQuery works with arrays differently than it works with it's on jQuery object wrapper. So to loop through an array you'd use jQuery.each() or $.each().
var myArray = ['x', 'y', 'z'];
$.each(myArray, function(idxArray, valArray) {
// code
});
concatenate "-string" to the end of it, and pass it as a class to be selected in jQuery
Now we can use the jQuery selector with .each() to find matching elements
var myArray = ['x', 'y', 'z'];
$.each(myArray, function(idxArray, valArray) {
var selector = "." + valArray = "-string";
$(selector).each(function(idxElement, valElement) {
var $this = $(valElement);
// or
var $this = $(this);
$this.fadeOut();
});
});
It's important to note that the second .each()
should only be used if you have specific logic to run after an item is found. If the code is the same for every element, then each is not needed:
var selector = "." + valArray = "-string";
// fadeOut all matching elements
$(selector).fadeOut();
It's also important to note that if the logic is as simple as your example, you should not need to loop at all. You can create a comma delimited string containing all the selectors.
var myArray = ["a","b","c","d"];
var selector = myArray
.map(s => "." + s + "-string")
.join();
$(selector).css("color", "red");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Black</div>
<div class="a-string">Red</div>
<div>Black</div>
<div class="b-string">Red</div>
<div>Black</div>
<div class="c-string">Red</div>
<div>Black</div>
<div class="d-string">Red</div>