JavaScript Code


jQuery – Set background image for element(s)



Set Background Image for HTML Element(s) using jQuery

Selected some HTML elements in the document, set background image for the elements using jQuery.

Solution

To set background image for selected HTML elements using jQuery, call css() function on the selected elements and pass the arguments: "background-image" CSS property, and required URL for image.

For example, the syntax to set a background image for all paragraphs in the document is

$("p").css("background-image", "url(http://javascriptcode.org/wp-content/uploads/2022/12/sample.png)");

Programs

1. Set background image, with image from specific URL, for paragraphs in the document.

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
      function myAction() {
        $("p").css("background-image", "url(http://javascriptcode.org/wp-content/uploads/2022/12/sample.png)");
      }
    </script>
  </head>
  <body>
    <button onclick="myAction()">Set background image for paragraphs</button>
    <br><br>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
  </body>
</html>

2. Set background image for div element with id myDiv, in the document.

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
      function myAction() {
        $("div#myDiv").css("background-image", "url(http://javascriptcode.org/wp-content/uploads/2022/12/sample.png)");
      }
    </script>
  </head>
  <body>
    <button onclick="myAction()">Set background image for div</button>
    <br><br>
    <div id="myDiv" style="width:200px;height:200px">This is a div.</div>
  </body>
</html>


copyright @2023