2

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.

jasonscript
  • 6,039
  • 3
  • 28
  • 43
Johnny Juarez
  • 248
  • 6
  • 18
  • `var imgElement = banner.getElementsByTagName('img')[0];` – Ja͢ck Jun 18 '15 at 06:17
  • Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Sebastian Simon Feb 26 '18 at 23:52

2 Answers2

7

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>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2

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....

John R
  • 2,741
  • 2
  • 13
  • 32
  • Thank you :) But I chose for my self Arun P Johny's second solution. Easier to understand and less to write :) But anyway thanx! – Johnny Juarez Jun 18 '15 at 07:43