casiokid
casiokid

Reputation: 119

Insert values from one loop to another

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

Answers (2)

Alex Char
Alex Char

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

.map()

Upvotes: 4

Arun P Johny
Arun P Johny

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

Related Questions