Get src and set as variable via class (id not available)

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?


solution

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;