Directly Changing the style Property

You can directly change the style property of an HTML element to update its background image. This approach does not require any additional functions.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        How to Change Background
        Image in JavaScript?
    </title>

    <style>
        body {
            text-align: center;
        }
        #GFG {
            width: 550px;
            height: 200px;
            margin: auto;
            background-image: url(
'https://www.w3wiki.org/wp-content/uploads/javascript.png');
            background-size: contain;
        }
    </style>
</head>

<body>
    <h1 id="GFG">
        Welcome to w3wiki
    </h1>
    <br>

    <button onclick="changeBackgroundImage()">
        Change Background Image
    </button>

    <script>
        function changeBackgroundImage() {
            let headingID = document.getElementById("GFG");
            headingID.style.backgroundImage = 
"url('https://media.w3wiki.org/wp-content/cdn-uploads/20210203170945/HTML-Tutorials.png')";
        }
    </script>
</body>

</html>

Output:

How to Change Background Image in javaScript?

This article will show you how to change the background color in JavaScript. Changing a background image in JavaScript involves modifying the style property of an HTML element to update its backgroundImage property. This can be done by selecting the element and setting its style.backgroundImage property to the new image URL.

Table of Content

  • Directly Changing the style Property
  • Using CSS Classes

Similar Reads

Approach 1: Directly Changing the style Property

You can directly change the style property of an HTML element to update its background image. This approach does not require any additional functions....

Approach 2: Using CSS Classes

Alternatively, you can define different CSS classes with different background images and then apply these classes to the element using JavaScript....

Contact Us