简体   繁体   中英

replace part of a background-image url with vanilla js for a series of images

I have a code that works well for changing a part of an src url of normal images

let svgz = document.querySelectorAll(".svg");
for (let i = 0; i < svgz.length; i++) {
  svgz[i].src = svgz[i].src.replace("light", "dark");
} 

I'd like to do the same with css background-image urls.

I have created this snippet based on the above mentioned one but its not working:

let svgbg = document.querySelectorAll(".svgbg");
for (let i = 0; i < svgbg.length; i++) {
    svgbg[i].style.backgroundImage = svgbg[i].style.backgroundImage.replace("light", "dark");
}

How can I change a background images url partially?

actually it works, it was interfering with setting the default background-image url with a variable when the page loads. If the background images is a single image independent of theme it works like charm.

This may be a case where the JS toggle method comes in useful, depending on exactly what is wanted of course. Code put up here in case of use to someone wanting to toggle between two background images (actually, between any two classes):

<style>
.svgbg {
  background-image: url(light.svg);/* replace with your light background url */
}
.svgbgdark {
  background-image:url(dark.svg);/* replace with your dark background url */
}
</style>
<div class="svgbg"></div>
<script>
let svgbg = document.querySelectorAll(".svgbg");
for (let i = 0; i < svgbg.length; i++) {
  svgbg.classList.toggle('svgbgdark');
}
</script>

Hi check the snippet below and let me know if this solves the problem.

 let svgbg = document.querySelectorAll(".svgbg"); let bg = " url('img_tree.png')" console.log(bg); for (let i = 0; i < svgbg.length; i++) { //set your updated bg path here bg = " url('https://cdn.pixabay.com/photo/2020/08/19/00/13/sea-5499649__340.jpg')" console.log(bg); svgbg[i].style.backgroundImage = bg }
 .svgbg { background-size: 100% auto; width: 100%; height: 100%; z-index: -1; position: absolute; }
 <div class="svgbg"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM