Change a portion of the CSS background-image URL using vanilla JavaScript for a set of pictures

My current code successfully updates part of an src URL for regular images.

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

Now, I want to achieve the same result with CSS background-image URLs.

I attempted to modify the previous code for background images, but it's not functioning correctly:

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

Any suggestions on how to partially change a background image URL?

Answer №1

Indeed, the solution proved successful! The issue stemmed from conflicts arising while attempting to establish a default background-image URL using a variable upon page initialization. When utilizing a background image that remains consistent regardless of the theme, the functionality operates seamlessly.

Answer №2

If you're looking to switch between two background images or classes in your code, the JS toggle method can be quite handy. Here's a snippet that demonstrates how it can be done:

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

Answer №3

Hey there, please have a look at the code snippet provided below and inform me if it resolves the issue:

let svgbg = document.querySelectorAll(".svgbg");
let bg = " url('img_tree.png')"

console.log(bg);

for (let i = 0; i < svgbg.length; i++) {
//update the background 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to include property in Mongoose find query object

After retrieving an object from the MongoDB database, I want to include an additional property before sending it as a response to the frontend using Express. obj = collection.find({}); obj[0].extra_property = "value"; res.send(obj); I am aware t ...

Switching the typeface within the content data

Recently, I incorporated this code: <div data-content="Reach" class="main-image"> along with the following CSS styling: .main-image:before { content: attr(data-content); I am now wondering if there is a method to adjust the font size and ...

Is it possible to programmatically include a getter method to a class in JavaScript or TypeScript?

My current focus is on TypeScript and I'm exploring the decorators functionality. I would greatly appreciate some guidance or expert knowledge on JavaScript capabilities in this area. I am curious about dynamically adding a getter method to a Prototy ...

Automatically relaunch NodeJS application upon app failure

I am looking for a way to automatically restart my NodeJS (Express) app after crashes with errors. I am familiar with the forever npm package, but all the examples I found were for running the app in development. My goal is to implement this in production ...

Choosing specific rows in a kogrid by clicking on a button within a column

My kogrid includes a single column with a view button for each row. I would like to show a popup containing the values of the selected row when the View button is clicked. How can I retrieve the values of the selected row in order to pass them into the p ...

Creating a Navigation Bar with a Dropdown Menu in HTML

Apologies if this question has been asked before, but I've searched everywhere and can't find an answer. All my searches just bring up dropdown menus with <nav></nav> Consider this table (serving as a navigation bar): <table cl ...

HTTP 400 Error: Bad Request Callback

I'm attempting to send data using REST API through jQuery AJAX. Here's the code I am using: $.ajax({ url: 'myurl', type: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify(j ...

Implement auto partial page refreshing in ASP.NET without using the UpdatePanel feature

Looking to implement auto partial page refresh in asp.net without sending excessive data through UpdatePanel. Considering using a webservice called by JavaScript instead, but unsure how to trigger it automatically rather than by button click event. Many e ...

Is it possible for Nextjs routing catchAll to coexist with a slug folder within a route?

When converting my pages to ISR, I encountered an issue with handling params and dynamic routes. One example is where article/?pageNumber=2 needs to be rewritten as article/2 in middleware for improved performance. However, this change in routing structure ...

Show information when table is clicked

I currently have a 9 x 9 table with unique content in each cell. Is there a way to enable the following functionality: Upon clicking on the text within a specific cell, all related content would be displayed right below that same cell? For instance, if ...

Tips for ensuring an element stays anchored at the bottom even when the keyboard is displayed

I recently encountered a situation on one of my pages where an element positioned at the bottom using absolute positioning was causing issues when the keyboard was opened, as it would move to the middle of the page unexpectedly. While this may seem like a ...

The JQuery .replaceWith method exclusively offers unprocessed HTML content

I'm experiencing a minor issue with my ajax response where it returns raw html and does not execute any scripts, resulting in the jquery ui scripts not being executed. Here are some details: I am currently working with ASP.NET MVC and I need to comm ...

Tips for positioning the footer at the bottom of the page

During the process of constructing a new website, I included a footer that is neatly positioned at the bottom of my screen. However, I noticed that on pages with minimal content, the footer does not remain fixed at the bottom: In order to ensure that the ...

Utilizing Gulp locally without the need for global installation or referencing the bin js file

I have a gulpfile.js that runs perfectly when I type 'gulp' into the command line. Essentially, the 'gulp' bash command just calls the specific js file outlined in 'package.json >> bin >> gulp' of the globally ins ...

How can I dynamically adjust an element's attribute as a user scrolls past it (creating a sticky effect)?

For instance, when you visit and try scrolling up, you will notice a bar displaying: "Typography Code Tables Forms Buttons Icons by Glyphicons" As you continue to scroll past the element, a class is added to alter the appearance. However, as you scrol ...

A step-by-step guide on executing a callback function once the animation has finished with frame-motion

I'm facing an issue with my component called AnimatedText. After the animation is complete, I want the words filled in the underlineLines prop to be underlined. How can I achieve this? I attempted using the onAnimationEnd function, but it didn't ...

Echo a JS variable into PHP and then insert a PHP file into an HTML element - a step-by-step guide!

Greetings to the wonderful community at stackoverflow, I am currently working on a variable code that allows for easy insertion of code from another file, such as a div. I am curious if it is possible to include a PHP file using JavaScript and JS variable ...

What is the process of integrating ES6 modules with app.get in a Node/Express routing application?

After researching the benefits of ES6 export, I made the decision to implement it in a NodeJS/Express project instead of using module exports. The MDN documentation explained that export is used as shown below: export function draw(ctx, length, x, y, color ...

Props in Vue components are exclusively accessible within the $vnode

Exploring the realm of Vue.js, I am tasked with constructing a recursive Component renderer that transforms JSON into rendered Vue components. The recursive rendering is functioning smoothly; however, the props passed to the createElement function (code b ...

Utilize a directive every instance

I need to implement an angular directive that triggers before all events like ng-click whenever the view value changes. This directive should be called as the first action when the view is changed. Check out the JSFiddle example. angular.module('myA ...