Reputation: 329
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.
Upvotes: 2
Views: 4688
Reputation: 62042
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">
Upvotes: 1
Reputation: 67525
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;
Upvotes: 5
Reputation: 1022
let img = document.querySelector('#thumb');
console.log(img.src);
If you use img.src, you'll see the source of your img tag.
Upvotes: 1
Reputation: 2168
You can get image src
like this,
var thumb = document.getElementById("thumb").src;
You don't need to use getElementsByTagName
.
Upvotes: 1