Get the HTML img tag src attribute value in JavaScript

I am sure that you must familiar with the HTML img tag. We all know that using this tag, we can display an image on a web page. All we have to do is just to give the image path inside the src attribute of the image tag.

Now, in this article, I am going to tell you how to get the img tag src attribute value in JavaScript.

Below is an example of how we can show an image on the web page with the HTML img tag:

<img id="my-img" src="cat.png">

Now we want to get the src value of the above HTML img tag. We can clearly see that the src attribute has path value “cat.png”. We want to get the value programmatically with JavaScript.

Also, read:

JavaScript code to get the HTML img tag src attribute value

Below is our JavaScript code to get src value from the above img tag that I have just used as the example:

var img_src = document.getElementById("my-img").src;
console.log(img_src);

If we run our code on the browser, we can see “directory/cat.png” in the console log. You can see that it returns the complete path of the src file.

So easy and simple. Isn’t it? We did it only in one line of code and the extra one line is just to show the value in the console log.

Here we have used the HTML image src property to get the attribute value. The src property of JavaScript HTML DOM can set or return the value of src attribute. In our case, we have used this property to return the attribute value.

Leave a Reply

Your email address will not be published. Required fields are marked *