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

Time:08-09

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 >
  <div >
    <div  data-flickity-bg-lazyload="https://imageurl.jpg"></div>
  </div>
  <div >
    <div  data-flickity-bg-lazyload="https://imageurl.jpg"></div>
  </div>
  <div >
    <div  data-flickity-bg-lazyload="https://imageurl.jpg"></div>
  </div>
  <div >
    <div  data-flickity-bg-lazyload="https://imageurl.jpg"></div>
  </div>
  <div >
    <div  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 >
  <div >
    <div  style="background-image:url(https://imageurl.jpg)"></div>
  </div>
  <div >
    <div  style="background-image:url(https://imageurl.jpg)"></div>
  </div>
  <div >
    <div  style="background-image:url(https://imageurl.jpg)"></div>
  </div>
  <div >
    <div  style="background-image:url(https://imageurl.jpg)"></div>
  </div>
  <div >
    <div  style="background-image:url(https://imageurl.jpg)"></div>
  </div>
</div>

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

CodePudding user response:

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 >
  <div >
    <div  data-flickity-bg-lazyload="https://www.fillmurray.com/100/100"></div>
  </div>
  <div >
    <div  data-flickity-bg-lazyload="https://www.fillmurray.com/100/100"></div>
  </div>
  <div >
    <div  data-flickity-bg-lazyload="https://www.fillmurray.com/100/100"></div>
  </div>
  <div >
    <div  data-flickity-bg-lazyload="https://www.fillmurray.com/100/100"></div>
  </div>
  <div >
    <div  data-flickity-bg-lazyload="https://www.fillmurray.com/100/100"></div>
  </div>
</div>

  • Related