javascript getElementsByTagName 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29944004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getElementsByTagName is not a function
提问by dcs
I am really struggling this. I am wanting to change the src attribute of an img tag and get the error message getElementsByTagName is not a function. The following is my test markup
我真的很挣扎这个。我想更改 img 标记的 src 属性并收到错误消息 getElementsByTagName is not a function。以下是我的测试标记
<html>
<body>
<div class="logo">
<img src="/a.jpg">
</div>
<script>
document.getElementsByClassName('logo').getElementsByTagName('img')[0].src ="/b.jpg";
</script>
</body>
</html>
Any advice is appreciated.
任何建议表示赞赏。
回答by Anthony Granger
getElementsByClassName return a collection. So you just have to do this :
getElementsByClassName 返回一个集合。所以你只需要这样做:
document.getElementsByClassName('logo')[0].getElementsByTagName('img')[0].src ="/b.jpg";
回答by CosX
document.getElementsByClassName
returns a list of all the classes in the document. Try the following code:
document.getElementsByClassName
返回文档中所有类的列表。试试下面的代码:
document.getElementsByClassName("logo")[0]
to get the first class.
document.getElementsByClassName("logo")[0]
获得第一堂课。
回答by Zee
回答by Haresh Shyara
Elements is a live HTMLCollection of found elements.
Elements 是已找到元素的实时 HTMLCollection。
Names is a string representing the list of class names to match; class names are separated by whitespace.
Names 是一个字符串,表示要匹配的类名列表;类名由空格分隔。
getElementsByClassName can be called on any element, not only on the document. The element on which it is called will be used as the root of the search.
getElementsByClassName 可以在任何元素上调用,而不仅仅是在文档上。调用它的元素将用作搜索的根。
document.getElementsByClassName('logo')[0].getElementsByTagName('img')[0].src ="/b.jpg";