Using .getAttribute in a loop to add styles

66 views Asked by At

First post on here. Hoping someone can help?!

I'm trying to add styles to a parallax carousel I've created by adding data-attributes in the HTML and then looping through each of the images, in the carousel, using JS. I'm able to get the 'data-background' added to the inline styles but the 'data-position' isn't.

Expected output

<div class="parallax-container parallax-scale" 
data-background="//localhost:3000/wp-content/uploads/2020/03/animage.jpg" 
data-position="50% 50%" data-swiper-parallax="1130.25" 
style="transform: translate3d(0px, 0px, 0px); background-image: url("//localhost:3000/wp-content/uploads/2020/03/animage.jpg"); background-position: 50% 50%;">

var list = document.getElementsByClassName('parallax-container');

for (var i = 0; i < list.length; i++) {
  var src = list[i].getAttribute('data-background');
  list[i].style.backgroundImage = "url('" + src + "')";
  var pos = list[i].getAttribute('data-position');
  list[i].style.backgroundPosition = pos;
  console.log(list[i])
}
<div class="parallax-container parallax-scale" data-background="//localhost:3000/wp-content/uploads/2020/03/animage.jpg" data-position="50% 50%">

0

There are 0 answers