To set or change background image of any element, you can make use of the backgroundImage property. We are going to use this property to accomplish our goal.
In the following example, we have multiple images in the images directory. We also have 4 button elements. Upon click of each button, we will pick one image from the images directory and set it as our background image. Please have a look over the code example and the steps given below.
HTML & CSS
We have 2 elements in the HTML file (div and button). The div element is just a wrapper for the button elements.
The background.jpg is our default background image for the body element.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
We have selected all the button elements using the document.querySelector() method and stored them in the btn1, btn2, btn3, and btn4 variables respectively.
We have attached the click event listener to all the button elements.
In the click event handler function of each button element, we are using the backbgroundImage property of the body element to replace the background image with one of the images present in the images directory.
In the case of the 4th click event handler function, we are not picking an image from the images directory using relative URL rather we are using an absolute URL. The browser will load the image from that absolute URL and then set it as our background image.