How get element's child and then child's src

2.3k views Asked by At

Hope somebody can help with this:

My Demo

  1. How can I get element's child with exact tag name (in this case img)?
  2. How can I get this child's attribute?

Next doesn't work:

var banner = document.getElementById('banner');
var imgElement = banner.getElementsByTagName('img');
var imgSrc = imgElement.getAttribute('src');

Last line returns imgElement.getAttribute is not a function. I guess it's because of second line, where I get object HTMLCollection...But why I got this and what I have to do to get what I want?

Thanx a lot in advance for any help.

2

There are 2 answers

0
Arun P Johny On BEST ANSWER

getElementsByTagName returns an HTMLCollection, so get the first element in the array and then its src

var imgSrc = imgElement[0].getAttribute('src'); 

var banner = document.getElementById('banner');
var imgElement = banner.getElementsByTagName('img');
var imgSrc = imgElement[0].getAttribute('src');
alert(imgSrc);
<a href="#" id="banner">
  <img src="http://placekitten.com/g/200/300" alt="kitten" />
</a>

Another solution is to use querySelector(will be little slower)

var imgElement = document.querySelector('#banner img');
var imgSrc = imgElement.getAttribute('src');
alert(imgSrc);

var imgElement = document.querySelector('#banner img');
var imgSrc = imgElement.getAttribute('src');
alert(imgSrc);
<a href="#" id="banner">
  <img src="http://placekitten.com/g/200/300" alt="kitten" />
</a>

1
John R On

Another alternative solution using children.

var banner = document.getElementById('banner');
var childImg = banner.children[0];
var imgSrc = childImg.getAttribute('src');
alert(imgSrc);

Hope this helps....