Javascript : get <img> src and set as variable?

If the img below is present

<img id="youtubeimg" src="http://i1.ytimg.com/vi/VK4ah66jBvE/0.jpg"/>

and the script is

<script>
var youtubeimgsrc = "something here"

document.write(''+youtubeimgsrc+'')
</script>

and the result should be http://i1.ytimg.com/vi/VK4ah66jBvE/0.jpg

what can i do to get the image source and set as a variable.


As long as the script is after the img, then:

var youtubeimgsrc = document.getElementById("youtubeimg").src;

See getElementById in the DOM specification.

If the script is before the img, then of course the img doesn't exist yet, and that doesn't work. This is one reason why many people recommend putting scripts at the end of the body element.


Side note: It doesn't matter in your case because you've used an absolute URL, but if you used a relative URL in the attribute, like this:

<img id="foo" src="/images/example.png">

...the src reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com, document.getElementById("foo").src would give you "http://www.example.com/images/example.png".

If you wanted the src attribute's content as is, without being resolved, you'd use getAttribute instead: document.getElementById("foo").getAttribute("src"). That would give you "/images/example.png" with my example above.

If you have an absolute URL, like the one in your question, it doesn't matter.


If you don't have an id on the image but have a parent div this is also a technique you can use.

<div id="myDiv"><img src="http://www.example.com/image.png"></div>

var myVar = document.querySelectorAll('#myDiv img')[0].src

How about this for instance :

var youtubeimgsrc = document.getElementById("youtubeimg").getAttribute('src');