Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  42] [ 6]  / answers: 1 / hits: 15440  / 9 Years ago, mon, february 16, 2015, 12:00:00

I'm trying to get the URL of a certain image out of the given HTML code



<div class=image_div_name>
<img src=http://www.thisistheimage.com alt=>
</div>


So this is my current code that should solve it:



var picture = document.getElementsByClassName(image_div_name);
var src = picture[0];


If I now print picture via console.log, I get the correct div:



<div class=image_div_name>
<img src=http://www.thisistheimage.com alt=>
</div>


However, if I want to access the src, it doesnt seem to work:



var src = picture[0].src;
console.log(src);


Gives back:



undedfined


If I try:



console.log(picture[0].innerHTML)


it gets better and I receive:



<img src=http://www.thisistheimage.com alt=>


However I'm looking for way to merely get the URL itself, as in:



http://www.thisistheimage.com


Can you help? What am I doing wrong?


More From » html

 Answers
34

It's because .image_div_name doesn't have a src attribute, you need to select the child img element.



Given the HTML you provided, you could access it using picture[0].children[0]:



var picture = document.getElementsByClassName(image_div_name);
var src = picture[0].children[0].src;


Rather than using picture[0].children[0], you could also use picture[0].firstElementChild to access the first child:



var picture = document.getElementsByClassName(image_div_name);
var src = picture[0].firstElementChild.src;





Since neither of the above methods gurentee that an img element will be selected (since you're selecting the first child element), it would probably be better to use something along these lines instead:



var src = document.querySelector('.image_div_name > img').src;


..or:



var picture = document.querySelectorAll(.image_div_name > img);
var src = picture[0].src;

[#67800] Saturday, February 14, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marques

Total Points: 366
Total Questions: 108
Total Answers: 111

Location: Burundi
Member since Wed, Nov 25, 2020
4 Years ago
;