Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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;

Solution 2:

You are not targeting the img, you are targeting the <div>, which is why the innerHTML property holds the <img> inside. (Images don't have innerHTML).

Select the <img> instead. I've used .querySelectorAll():

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

Solution 3:

You can do this (if you are 100% sure your div only has a child <img>):

var node = document.getElementsByClassName("image_div_name");
var src = node[0].children[0].src;
console.log(src);

Solution 4:

Although Andy's answer is helpful I recommend.

var picture = document.getElementsByClassName("image_div_name")[0].getElementsByTagName("img")[0];
var src = picture.getAttribute('src');

Post a Comment for "Get Src And Set As Variable Via Class (id Not Available)"