This post will discuss how to change the background image of a div with JavaScript/jQuery and CSS.

1. Using JavaScript

In plain JavaScript, you can directly modify the backgroundImage CSS property of the image to set one or more background images on an element. The following example demonstrates this:

JS


HTML



Edit in JSFiddle

2. Using jQuery

With jQuery, you can use the .css() method to change the background image on an element. We can do this with the background-image CSS property.

jQuery


HTML



Edit in JSFiddle

 
The .css() method can also take a single object of key-value pairs. So, the code can be shortened to:

jQuery


HTML



Edit in JSFiddle

3. Using jQuery + CSS

Another plausible solution is to specify the background-image in a CSS class and apply that class to the image element. This can be easily done using the jQuery’s .addClass() method. To overwrite an existing class, you can add !important declarations.

jQuery


CSS


HTML



Edit in JSFiddle

4. Non-JavaScript solution

You can also directly apply the background-image CSS property without using any JavaScript. The following example demonstrates this:

CSS


HTML



Edit in JSFiddle

That’s all about changing the background image of a div with JavaScript, jQuery, and CSS.