How to get a the url of an image from id in Javascript

4.3k views Asked by At

I know it's such a beginner thing. So I have this image in a div with the id thumb.

<img id="thumb" src="https://url-to-a-image">

And this Javascript that it's a magnify script:

<script type="text/javascript">
    var myImgSrc = document.getElementById("thumb").getElementsByTagName("img") 
[0].src;
    var evt = new Event(),
    m = new Magnifier(evt);
    m.attach({
        thumb: '#thumb',
        large: 'myImgSrc',
        largeWrapper: 'preview'
    });
</script>

As you can see I'm trying to get the image using myImgSrc and then I'm trying to use in the large: 'myImgSrc'. When I put the a fixed url in large: fixed-url-to-the-image, it works fine.

4

There are 4 answers

0
Zakaria Acharki On BEST ANSWER

The element with #thumb id is the tag img it self, the current selector will not return the src value, so it should be simply:

var myImgSrc = document.getElementById("thumb").src;
0
Bhavin On

You can get image src like this,

var thumb = document.getElementById("thumb").src;

You don't need to use getElementsByTagName.

0
tlm On
let img = document.querySelector('#thumb');
console.log(img.src);

If you use img.src, you'll see the source of your img tag.

0
ADyson On

getElementsByTagName is superfluous - you already have the exact element you want - you selected it by its ID. You'd only need getElementsByTagName if you wanted to get one or more elements by their tag and work on them all, rather than identifying one precisely.

So actually the solution is very simple - just get the src attribute of the ID-selected element directly. Working demo:

var myImgSrc = document.getElementById("thumb").src;
console.log(myImgSrc);
<img id="thumb" src="https://url-to-a-image">