Javascript Reference - HTML DOM Image src Property








The src attribute specifies the URL of an image.

The src property sets or gets the value of the src attribute of an image.

Browser Support

src Yes Yes Yes Yes Yes

Syntax

Return the src property.

var v = imageObject.src

Set the src property.

imageObject.src=URL

Property Values

Value Description
URL Specifies the URL of the image.




Return Value

A String type value representing the URL of the image.

Example

The following code shows how to get the URL of an image.


<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="http://java2s.com/style/demo/border.png" width="100" height="100">
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from  w w  w.  j  ava  2  s.c  om-->
    var x = document.getElementById("myImg").src;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to change the URL of an image.


<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="http://java2s.com/style/demo/border.png" width="100" height="100">
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from ww  w .  j a  va2s. com-->
    document.getElementById("myImg").src = "http://java2s.com/style/demo/Firefox.png";
}
</script>

</body>
</html>

The code above is rendered as follows: