HTML - DOM src Property



The HTML DOM src property is used to get (retrieve) or set (update) the source for an image (<img>) element in HTML.

It returns the current source URL of the image, and when modified, it updates the "src" attribute of the image, allowing you to change the source file, path, or link destination dynamically.

Syntax

Following is the syntax of the HTML DOM src (to get the src attribute) property −

imageObject.src

To update (set) the src property, use the following syntax −

imageObject.src = new_source

Parameters

Since it is a property, it does not accept any parameters.

Return value

This property returns the current source of the image element as a string.

Example 1: Retrieving the current source of an "img" element

The following is the basic example of the HTML DOM src property.

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM src</title>
</head>
<body>
<p>The source of an image is displaed below: </p>
<p>My Image: </p>
<img src ="https://www.tutorialspoint.com/images/logo.png" id="my_img">
<p id="result"></p>
<script>
   let my_img = document.getElementById("my_img");
   document.getElementById('result').innerHTML = "The source of the above image is: " + my_img.src;
</script>
</body>
</html>

Example 2: Updating the current source of an "img" element

Here is another example of using the HTML DOM src property. We used this property to update (change) the source of an image −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM src</title>
<style>
   img{
      width: 300px;
      height: 200px;
      border: 2px solid green;
      border-radius: 10px;
   }
</style>
</head>
<body>
<p>Click the below button to update the source of an image:</p>
<p>My Image: </p>
<img src ="https://www.tutorialspoint.com/images/logo.png" id="my_img"><br><br>
<button id="change_btn">Update</button>
<p id="result"></p>
<script>
   document.getElementById('change_btn').addEventListener("click", ()=>{
      let my_img = document.getElementById("my_img");
      my_img.src = "https://www.tutorialspoint.com/static/images/hero.png";
      document.getElementById('result').innerHTML = "The source of an image has been updated...";
   });
</script>
</body>
</html>

Supported Browsers

Property Chrome Edge Firefox Safari Opera
value Yes Yes Yes Yes Yes
html_dom.htm
Advertisements