admin管理员组

文章数量:1393850

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.

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.

Share Improve this question edited Aug 7, 2018 at 15:46 Zakaria Acharki 67.5k15 gold badges78 silver badges106 bronze badges asked Aug 7, 2018 at 15:41 danskidanski 3291 gold badge6 silver badges17 bronze badges 1
  • 4 Try like this, var thumb = document.getElementById("thumb").src; ? – Bhavin Commented Aug 7, 2018 at 15:43
Add a ment  | 

4 Answers 4

Reset to default 5

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;

You can get image src like this,

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

You don't need to use getElementsByTagName.

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

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

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">

本文标签: magnifierjsHow to get a the url of an image from id in JavascriptStack Overflow