Search code examples
javascripthtmlgetelementsbytagname

getElementsByTagName inside a div class in Javascript


I have a div class with multiple images in there which do not have a specific id.

want that when you click on the image, the logo gets displayed at a different location.

<div class="gs-image-box"> <a href="http://www.car-logos.org/audi" target="_blank" class="gs-image gs-image-scalable"><img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTfBGu4EqulBN9htr_1tQD_xHtayahqbhMYc31ZhTh_PNuga76Wx4_Asg" title="Audi | Audi Car logos and Audi car company logos worldwide" class="gs-image gs-image-scalable" style="width: 84px; height: 84px;"></a>
</div>
<div class="gs-image-box"> <a href="http://logok.org/audi-logo/" target="_blank" class="gs-image gs-image-scalable"><img src="http://t2.gstatic.com/images?q=tbn:ANd9GcRFmGT17faZJ1OBpW8IR7ZuQr4GqmLM1oWuu-RTo3JJHaRur-p17FuMCVI" title="Audi logo | Logok" class="gs-image gs-image-scalable" style="width: 112px; height: 84px;"></a>
</div>

Therefore I use the getElementsByTagName, a detailed code here http://fiddle.jshell.net/g1e25r6p/1/

However, it only works for the first tag [0] and not for the second one [1]

I'm stuck on this for days now, does anyone have an idea, how to do that or what I am doing wrong?


Solution

  • First issues:

    var badgeimg2 = imageresult[1].getElementsByTagName('img')[1];
    

    Should be

    var badgeimg2 = imageresult[1].getElementsByTagName('img')[0];
    

    Second issue (in the event listener code of badgeimg2):

    var imgsrc = badgeimg.src;
    

    Should be:

    var imgsrc = badgeimg2.src;