Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 980
Yusaf Khaliq Avatar asked Oct 24 '11 21:10

Yusaf Khaliq


1 Answers

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.

like image 177
T.J. Crowder Avatar answered Sep 23 '22 15:09

T.J. Crowder