Change background image of a div using JavaScript, jQuery, and CSS
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
|
1 2 3 4 5 6 |
var url = "https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072823_1280.jpg"; var div = document.getElementById("container"); div.style.backgroundImage = `url(${url})`; div.style.width = "640px"; div.style.height = "374px"; |
HTML
|
1 2 3 4 5 |
<html> <body> <div id="container"></div> </body> </html> |
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
|
1 2 3 4 5 6 7 |
var url = "https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072823_1280.jpg"; $(document).ready(function() { $("#container").css("background-image", `url(${url})`) .css("width", 640) .css("height", 374); }) |
HTML
|
1 2 3 4 5 |
<html> <body> <div id="container"></div> </body> </html> |
The .css() method can also take a single object of key-value pairs. So, the code can be shortened to:
jQuery
|
1 2 3 4 5 6 7 8 9 |
var url = "https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072823_1280.jpg"; $(document).ready(function() { $("#container").css({ "background-image": `url(${url})`, "width": 640, "height": 374 }); }) |
HTML
|
1 2 3 4 5 |
<html> <body> <div id="container"></div> </body> </html> |
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
|
1 2 3 |
$(document).ready(function() { $("#container").addClass("nature"); }) |
CSS
|
1 2 3 4 5 |
.nature { background-image: url('https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072823_1280.jpg'); width: 640px; height: 374px; } |
HTML
|
1 2 3 4 5 |
<html> <body> <div id="container"></div> </body> </html> |
4. Non-JavaScript solution
You can also directly apply the background-image CSS property without using any JavaScript. The following example demonstrates this:
CSS
|
1 2 3 4 5 6 |
div#container { background-image: url('https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072823_1280.jpg'); width: 640px; height: 374px; } |
HTML
|
1 2 3 4 5 |
<html> <body> <div id="container"></div> </body> </html> |
That’s all about changing the background image of a div with JavaScript, jQuery, and CSS.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)