admin管理员组

文章数量:1404576

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.

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.

Share Improve this question edited Jun 18, 2015 at 6:30 jasonscript 6,1783 gold badges30 silver badges45 bronze badges asked Jun 18, 2015 at 6:06 Johnny JuarezJohnny Juarez 2487 silver badges18 bronze badges 2
  • var imgElement = banner.getElementsByTagName('img')[0]; – Ja͢ck Commented Jun 18, 2015 at 6:17
  • Possible duplicate of What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return? – Sebastian Simon Commented Feb 26, 2018 at 23:52
Add a ment  | 

2 Answers 2

Reset to default 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./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./g/200/300" alt="kitten" />
</a>

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

本文标签: javascriptHow get element39s child and then child39s srcStack Overflow