Open In App

How to change the src attribute of an img element in JavaScript / jQuery ?

The task is to change the src attribute of the <img> element by using JQuery and JavaScript.

Example 1: This example changes the src attribute of image by using JavaScript.




<!DOCTYPE HTML> 
<html
    <head
        <title
            Change the src attribute
            of an img tag
        </title>     
    </head
      
    <body style = "text-align:center;"
          
        <h1 style = "color:green;"
            GeeksForGeeks 
        </h1>
          
        <p id = "GFG_UP" style =
            "font-size: 15px; font-weight: bold;">
        </p>
          
        <img id = "img" src =
          
        <br>
          
        <button onclick = "GFG_Fun()">
            click here
        </button>
          
        <p id = "GFG_DOWN" style
            "color:green; font-size: 20px; font-weight: bold;">
        </p>
          
        <script
            var up = document.getElementById('GFG_UP');
            up.innerHTML = "Click on button to change the src of image";
            var down = document.getElementById('GFG_DOWN'); 
              
            function GFG_Fun() {
                document.getElementById("img").src =
                down.innerHTML = "src attribute changed";
            }
        </script
    </body
</html>

Output:

Example 2: This example changes the src attribute of image by using JQuery.




<!DOCTYPE HTML> 
<html
    <head
        <title
            Change the src attribute of
            an img tag using jQuery
        </title>
          
        <script src =
        </script>
    </head
  
    <body style = "text-align:center;">
           
        <h1 style = "color:green;"
            GeeksForGeeks 
        </h1>
          
        <p id = "GFG_UP" style
            "font-size: 15px; font-weight: bold;">
        </p>
          
        <img id = "img" src =
          
        <br>
          
        <button onclick = "GFG_Fun()">
            click here
        </button>
          
        <p id = "GFG_DOWN" style
            "color:green; font-size: 20px; font-weight: bold;">
        </p>
          
        <script
            $("#GFG_UP").text("Click on button to change the src of image");
            $('button').on('click', function(e) {
                $('#img').prop('src',
                $("#GFG_DOWN").text("src attribute changed");
            }); 
        </script
    </body
</html>                    

Output:


Article Tags :