Search code examples
javascriptselectors-api

Vanilla JS - grab data-attribute value, add style attribute with value; remove data attribute


I've been tasked to brute force override a carousel using the data attribute URL in an added style attribute.

So, I have five slides like this (div with bg image is nested in parent slide div):

<div class="slider">
  <div class="slide">
    <div class="slide-bg" data-flickity-bg-lazyload="https://imageurl.jpg"></div>
  </div>
  <div class="slide">
    <div class="slide-bg" data-flickity-bg-lazyload="https://imageurl.jpg"></div>
  </div>
  <div class="slide">
    <div class="slide-bg" data-flickity-bg-lazyload="https://imageurl.jpg"></div>
  </div>
  <div class="slide">
    <div class="slide-bg" data-flickity-bg-lazyload="https://imageurl.jpg"></div>
  </div>
  <div class="slide">
    <div class="slide-bg" data-flickity-bg-lazyload="https://imageurl.jpg"></div>
  </div>
</div>

And I need to use the data-flickity-bg-lazyload attribute value in an (added) style attribute background-image: url(...) so it ends up like this:

<div class="slider">
  <div class="slide">
    <div class="slide-bg" style="background-image:url(https://imageurl.jpg)"></div>
  </div>
  <div class="slide">
    <div class="slide-bg" style="background-image:url(https://imageurl.jpg)"></div>
  </div>
  <div class="slide">
    <div class="slide-bg" style="background-image:url(https://imageurl.jpg)"></div>
  </div>
  <div class="slide">
    <div class="slide-bg" style="background-image:url(https://imageurl.jpg)"></div>
  </div>
  <div class="slide">
    <div class="slide-bg" style="background-image:url(https://imageurl.jpg)"></div>
  </div>
</div>

Is there an elegant way to do this with a querySelectorAll + loop + removeAttribute + addAttribute?


Solution

  • If I understood you correctly, then you can try this example:

    document.querySelectorAll('.slider .slide-bg').forEach(el => {
      el.style.backgroundImage = `url(${el.dataset.flickityBgLazyload})`;
      delete el.dataset.flickityBgLazyload;
    })
    .slide-bg {
      width: 100px;
      height: 100px;
    }
    <div class="slider">
      <div class="slide">
        <div class="slide-bg" data-flickity-bg-lazyload="https://www.fillmurray.com/100/100"></div>
      </div>
      <div class="slide">
        <div class="slide-bg" data-flickity-bg-lazyload="https://www.fillmurray.com/100/100"></div>
      </div>
      <div class="slide">
        <div class="slide-bg" data-flickity-bg-lazyload="https://www.fillmurray.com/100/100"></div>
      </div>
      <div class="slide">
        <div class="slide-bg" data-flickity-bg-lazyload="https://www.fillmurray.com/100/100"></div>
      </div>
      <div class="slide">
        <div class="slide-bg" data-flickity-bg-lazyload="https://www.fillmurray.com/100/100"></div>
      </div>
    </div>