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

Yusaf Khaliq picture Yusaf Khaliq · Oct 24, 2011 · Viewed 257.7k times · Source

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.

Answer

T.J. Crowder picture T.J. Crowder · Oct 24, 2011

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.