Reputation: 119
I have two loops and I want to loop through loop1 and insert it's data-attribute value into loop2. Using the below how could I do this?
Thanks!
$(".groupA[data-background]").each(function(i){
var backgroundData = $(this).data('background');
})
$(".groupB").each(function(i){
var newBackground = $(this).attr('style'); ???
})
EDIT: I tried nested loops but it just repeats the same 'backgroundData'. What am I missing?
$(".swatch[data-background]").each(function(i){
var backgroundData = $(this).data('background');
console.log(backgroundData);
$('swatch').each(function(i){
$(this).attr('style', backgroundData )
})
})
Upvotes: 2
Views: 80
Reputation: 33218
You can save the values in an array using map and using in second loop like:
var backgroundData = $(".groupA[data-background]").map(function(i) {
return $(this).data('background');
});
$(".groupB").each(function(i) {
var newBackground = $(this).attr('style', "background:" + backgroundData[i]);
});
References
Upvotes: 4
Reputation: 388316
I think what you are trying to do is to apply the backgound color of groupB
elements based on the data-background
attribute groupA
element in the same index
var $gbs = $(".groupB");
$(".groupA[data-background]").each(function (i) {
$gbs.eq(i).css('background-color', $(this).data('background'))
})
Upvotes: 2