How to change background image of a div with JavaScript/jQuery and CSS?

Today, We want to share with you set background image javascript.In this post we will show you background image size, hear for javascript change background image we will give you demo and example for implement.In this post, we will learn about how to Change a background image in react native? with an example.

How To Set a Background Using JavaScript?

Example 1: index.html

<!DOCTYPE html>
<html>
   <head>
      <style>
         #cart-data {
            border: 2px dashed blue;
            width: 800px;
            height: 600px;
            background: url('https://www.yourdomain_name.com/api/domain/pakainfo_logo.jpg') no-repeat;
         }
      </style>
   </head>
   <body>
      <button onclick="display()">Change size of background image</button>
      <div id="cart-data">
      </div>
      <script>
         function display() {
            document.getElementById("cart-data").style.backgroundSize = "150px 200px";
         }
      </script>
   </body>
</html>

How to Change background-image property from JavaScript?

Example 2: Use the jQuery CSS() Method

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Setting background-image CSS Property - www.pakainfo.com</title>
<style>
    .demo{
        width: 500px;
        height: 300px;
        border: 5px solid #333;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var imageUrl = "images/pakainfo.jpg";
        $(".demo").css("background-image", "url(" + imageUrl + ")");
    });    
});
</script>
</head>
<body>
    <div class="demo"></div>
    <p><button type="button">Change Background Image</button></p>
</body>
</html>

set attribute javascript background image

Change attribute javascript background image

document.body.style.backgroundImage = "url('pakainfo.png')";

set an attribute background image javascript

function setBackCustom() {

   var flacCnt = 3;
   var dir = 'http://www.your_domain_name.com/_wordpress/img/';

   var generatedCnt = (Math.floor(Math.random() * flacCnt));

   var images = ['tamilrokers.png', 'bolly4u.png', 'khatrimaza.png'];

   document.getElementById('banner').setAttribute("style", "background-image: url(" + dir + images[generatedCnt] + ");background-repeat: no-repeat;background-size: 388px 388px");
}

setBackCustom();

I hope you get an idea about javascript get background-image url.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.