I'm trying to pass an array to my .each JQuery code, but it is passing just the numbers 0, 1, 2, 3,... instead of the string values.
My code to define the variable is:
var accessoriesCats = [ 'Beaded Accessories', 'Cufflinks', 'Flip Flops', 'Floral Accessories', 'Foot Jewelry', 'Hair Accessories', 'Hankies', 'Jewelry', 'Leg Garters', 'Purses', 'Shoe Stickers', 'Something Blue', 'Tiaras', 'Totes' ];
Here is my entire code:
<script>
if (window.location.href.indexOf("category-s/2022.htm") != -1) {
var accessoriesCats = [ 'Beaded Accessories', 'Cufflinks', 'Flip Flops', 'Floral Accessories', 'Foot Jewelry', 'Hair Accessories', 'Hankies', 'Jewelry', 'Leg Garters', 'Purses', 'Shoe Stickers', 'Something Blue', 'Tiaras', 'Totes' ];
$('#content_area > table:nth-child(6) > tbody > tr > td > table:nth-child(1) > tbody > tr > td > table > tbody').find('a').each(function(accessoriesCats){
$(this).append('<span class="promo__text">' + accessoriesCats + '</span>');
$(this).removeClass('smalltext colors_text').addClass('subcatRollover');
});
}
</script>
Basically what I want to get with the very first .append is:
<span class="promo__text">Beaded Accessories</span>
but instead I get
<span class="promo__text">0</span>
2 Answers 2
Use this:
<script>
if (window.location.href.indexOf("category-s/2022.htm") != -1) {
var accessoriesCats = [ 'Beaded Accessories', 'Cufflinks', 'Flip Flops', 'Floral Accessories', 'Foot Jewelry', 'Hair Accessories', 'Hankies', 'Jewelry', 'Leg Garters', 'Purses', 'Shoe Stickers', 'Something Blue', 'Tiaras', 'Totes' ];
$('#content_area > table:nth-child(6) > tbody > tr > td > table:nth-child(1) > tbody > tr > td > table > tbody').find('a').each(function(i){
$(this).append('<span class="promo__text">' + accessoriesCats[i] + '</span>');
$(this).removeClass('smalltext colors_text').addClass('subcatRollover');
});
}
</script>
answered Jun 4, 2015 at 17:53
vakata
3,8961 gold badge19 silver badges31 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Per the docs, the first param of .each on an array is the index, the second is the item (http://api.jquery.com/jquery.each/)
.each(function(index, accessoriesCats) {
^^^ADD INDEX
answered Jun 4, 2015 at 17:51
tymeJV
105k14 gold badges165 silver badges158 bronze badges
Comments
lang-js
accessoriesCatsarray as parameter to the.eachfunction. You are iterating all theaelements.