I have the following html hierarchy:
...
<div class="custom-img-wrapper">
<a target="_blank" class="link-d" href="#"><img class="custom-below-img" src="some source"></a>
<h3><a target="_blank" class="link-d" href="#">some text</a></h3>
</div>
<div class="custom-img-wrapper">
<a target="_blank" class="link-d" href="#"><img class="custom-below-img" src="some source"></a>
<h3><a target="_blank" class="link-d" href="#">some text</a></h3>
</div>
...
and i am going over the links with this for loop :
var x = document.getElementsByClassName("link-d");
for (i = 0; i < x.length; i++) {
x[i].href = link;
}
now my question is how can i save the src of the image which is inside the link, so i'll get somwthing like this:
var x = document.getElementsByClassName("link-d");
for (i = 0; i < x.length; i++) {
var link_of_image_inside_node = x[i].????
x[i].href = link;
}
i know i can loop over the custom-below-image but that's not what i need, and im looking for a pure JavaScript no jQuery solution any idea? thx
asked Mar 27, 2016 at 14:42
yariv bar
9763 gold badges20 silver badges46 bronze badges
1 Answer 1
If a tags first child element is image then
var link_of_image_inside_node = x[i].firstChild.src;
OR
var link_of_image_inside_node = x[i].children[0].src; //ignores all the text before img tag
where x[i] is the anchor element
answered Mar 27, 2016 at 14:46
bugwheels94
32.2k3 gold badges43 silver badges62 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Grundy
firstChild can return TextNode alsobugwheels94
@Grundy then the
x[i].children[0].src will be handyGrundy
methinks, this can be noted in answer :-)
bugwheels94
@Grundy done however you can also edit any answer if you feel like it :)
Grundy
I know :-) i just notice that first variant can return wrong result :-) solution you suggest self
default