Reputation: 5
I have several classes with the names like so:
A dynamic part and a constant one. I have made an array containing the dynamic parts (x, y, z).
I want to loop through the array, take each name, concatenate "-string" to the end of it, and pass it as a class to be selected in jQuery.
Sort of like:
$(classList).each(function () {
let newClass = '.' + this + '-string'
$('.this-string')...
}
Is this possible and how would I go about it? Cheers.
Upvotes: 0
Views: 1587
Reputation: 54638
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>
Upvotes: 1
Reputation:
$.each
is used for iteration of the array. Which takes two arguments [index, element]
.
The element
is the element of an array. Don't use this
because it's not recommended!
$(classList).each((idx, elem) => {
$('.'+elem+'-string')
});
To use the native method we'll use the [].forEach
or for...of
iteration.
NOTE: for...of
method has only support from ES6.
// for...of loop
for(i of elem)
$(`.${elem}-string`)
// forEach loop
elem.forEach(function(elem) {
$('.'+elem+'-string')
});
Upvotes: 1
Reputation: 514
Some general issues with your usage of .each
. Try:
$(classList).each(function(idx, cls) {
let newClass = '.' + cls + '-string';
$(newClass) ...
});
Upvotes: 0