HOWTO · JavaScript
How to Set Background Image of a Div via Function in JavaScript
Learn how to set a div’s background image with a JavaScript function, switch predefined backgrounds with CSS classes, and understand when an img element is content rather than a background.
On this page
Changing a div’s background from a JavaScript function is a direct way to respond to a click or another event. Set the element’s backgroundImage style to a CSS url(...) value, and make sure the div has visible dimensions. For a small set of predefined images, switching CSS classes keeps the image choices in CSS. An img element displays content inside a div; it does not set the div’s background.
How a div Background Image Works
A CSS background-image is painted behind an element’s content. It does not add an image to the document’s content structure, so it is useful for decoration or imagery that should sit behind text. The div still needs visible width and height, content, or another layout rule; otherwise there may be no area in which to see the background.
The CSS property is background-image, while JavaScript accesses the corresponding style property as backgroundImage. Assign a string such as url("/images/forest.jpg") to that property. Use a URL that resolves from the page and that the browser can load. If an image is decorative, a background avoids adding it to the accessibility tree; use an img with meaningful alternative text when the image itself conveys content.
Set a Background Image in a JavaScript Function
Pass the image URL to a function and update the target element’s inline style. The first example is a small runnable JavaScript illustration of the assignment: its style object stands in for an element’s style, so it demonstrates the function’s input and resulting CSS value without claiming to run a browser DOM.
Run this example:
function setBackgroundImage(element, imageUrl) {
element.style.backgroundImage = `url("${imageUrl}")`;
}
const hero = { style: {} };
setBackgroundImage(hero, "/images/forest.jpg");
console.log(hero.style.backgroundImage);
url("/images/forest.jpg")
For a real page interaction, use markup with a div and button. The listener calls the same function after both elements have been parsed. Replace the sample URL with an image your page can load. This browser-page example is shown as source and has no claimed runtime output.
<div id="hero" class="hero">Featured content</div>
<button id="change-background" type="button">Change background</button>
<style>
.hero {
min-height: 12rem;
padding: 1rem;
background-position: center;
background-size: cover;
}
</style>
<script>
function setBackgroundImage(imageUrl) {
const element = document.getElementById("hero");
if (!element) return;
element.style.backgroundImage = `url("${imageUrl}")`;
}
const button = document.getElementById("change-background");
button.addEventListener("click", () => {
setBackgroundImage("/images/forest.jpg");
});
</script>
The script follows the markup, so the div and button exist when JavaScript looks them up. The CSS gives the div visible height and scales the background to cover it. If you move the script into a separate file, load it with defer or place it after the markup so the elements are available first. For untrusted or arbitrary URLs, validate the source according to your application’s rules before using it in CSS.
Switch Background Images with CSS Classes
When users choose among a fixed set of backgrounds, define the choices in CSS and let JavaScript select a class. For example, the CSS rules can be written inline as .hero--forest { background-image: url("/images/forest.jpg"); } and .hero--ocean { background-image: url("/images/ocean.jpg"); }. Give the div a base class with its dimensions and presentation, then use classList to switch between the two image classes.
A class-based function can remove both choice classes before adding the requested one: element.classList.remove("hero--forest", "hero--ocean"); element.classList.add(imageClass);. This keeps the available image names explicit and avoids accumulating conflicting classes. Use this approach when the choices are predefined and CSS owns the visual presentation. Use a direct backgroundImage assignment when the URL is dynamic or comes from application data.
Why an img Element Is Not a Background Image
Creating an img with document.createElement("img"), assigning its src, and appending it to a div makes the image a child of that div. It remains content in the page layout; setting display: none hides it and does not turn it into a background. Use this technique when the image should be a visible, semantic part of the content, or when you need to prepare an image element itself. For a background behind other content, set backgroundImage or apply a CSS class instead.
Choose and Test the Right Approach
Use CSS alone when the background is fixed. Choose a direct style update for a dynamic URL, or classes for a short list of designed states. CSS supports multiple backgrounds through comma-separated layers in background-image; the first listed layer is painted on top. Keep the layers in CSS or assign the full comma-separated value from JavaScript when the combination changes dynamically.
To troubleshoot a missing image, check that the ID lookup returns the intended element, inspect the computed background-image value, open the image URL directly, and confirm the div has visible dimensions. A browser’s network panel can show failed requests. Images from another origin may be blocked by server policy or require permission; using an external URL does not grant rights to the image. To preload an image, create an Image object and set its src before switching the background; preloading can reduce delay, but does not guarantee that a later request will succeed. These are practical checks to perform in your page, not checks reported as run here.