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.
This question is related to
javascript
image
src
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
in this situation, you would grab the element by its id using getElementById
and then just use .src
var youtubeimgsrc = document.getElementById("youtubeimg").src;
var youtubeimgsrc = document.getElementById('youtubeimg').src;
document.write(youtubeimgsrc);
Here's a fiddle for you http://jsfiddle.net/cruxst/dvrEN/
How about this for instance :
var youtubeimgsrc = document.getElementById("youtubeimg").getAttribute('src');
Use JQuery, its easy.
Include the JQuery library into your html file in the head as such:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
(Make sure that this script tag goes before your other script tags in your html file)
Target your id in your JavaScript file as such:
<script>
var youtubeimcsrc = $('#youtubeimg').attr('src');
//your var will be the src string that you're looking for
</script>
Source: Stackoverflow.com