Skip to content
Related Articles

Related Articles

Improve Article

How to get a div’s background image with jQuery ?

  • Last Updated : 31 Mar, 2021
Geek Week

The task is to get a div’s background image with jQuery. You can achieve this task by using the CSS() method in jQuery. 

In simple words, we need to create an empty div and on click event, the empty div will get the image as a background.

CSS(): This is an inbuilt method in jQuery to add the CSS property but in this case, we need to provide complete property using the URL() method.

Syntax:

  • The following syntax will return the background-color value of the first matched element.



    css("property_name");
  • This syntax will set the background-color value for all matched elements.

    $("p").css("background-color", "colorName");

URL(): This is a CSS function that is used to include a file. It accepts a single parameter URL in string format.

Syntax:

url(" <string> <url-modifier> ")

Example 1: First, create an empty div with a button. Map that button to CSS() method in jQuery. Use an image to place in the div element after the button was clicked.

HTML




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <style>
      .box {
        width: 600px;
        height: 500px;
        border: 6px solid green;
      }
    </style>
    <script src=
    <script>
      $(document).ready(function () {
        $("button").click(function () {
          var imageUrl = "gfg.jpg";
          $(".box").css("background-image", "url(" + imageUrl + ")");
        });
      });
    </script>
  </head>
  <body>
    <div class="box"></div>
  
    <p><button type="button">
         click here to see the background img.
       </button>
    </p>
  </body>
</html>

Output:

  • Before click: 
  • After click : 

Example 2:

HTML




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <style>
      .box {
        width: 600px;
        height: 500px;
        border: 6px solid rgb(61, 65, 61);
      }
    </style>
    <script src=
    </script>
    <script>
      $(document).ready(function () {
        $("button").click(function () {
          var imageUrl = "g.jpg";
          $(".box").css("background-image", "url(" + imageUrl + ")");
        });
      });
    </script>
  </head>
  <body>
    <div class="box"></div>
  
    <p><button type="button">click here !!</button></p>
  
    <style>
      button {
        background-color: blueviolet;
        align-items: center;
        margin-left: 250px;
      }
    </style>
  </body>
</html>

Output:

  • Before click:

  • After click: 




My Personal Notes arrow_drop_up
Recommended Articles
Page :