admin管理员组文章数量:1404576
Hope somebody can help with this:
My Demo
- How can I get element's child with exact tag name (in this case
img
)? - 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
- How can I get element's child with exact tag name (in this case
img
)? - 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
2 Answers
Reset to default 7getElementsByTagName 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
版权声明:本文标题:javascript - How get element's child and then child's src - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744840359a2627887.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论