[英]Can't select child elements using getElementsByTagName
Here is the HTML code: 这是HTML代码:
<span class="holder">
<a href="/menu/page1">Navigate</a>
</span>
I want to select all such tags with class holder and then under these holders I want to change href of a
tag. 我想选择所有这些变量与类持有人,然后根据这些人我想改变的HREF
a
标签。
What I have tried: 我尝试过的
var holders = document.getElementsByClassName('holder'),
i = holders.length;
while(i--) {
holders[i].getElementsByTagName('a').href = "http://www.google.com";
}
But the above code does not work. 但是上面的代码不起作用。 It does not change the href from
/menu/page1
to my custom link. 它不会将href从
/menu/page1
更改为我的自定义链接。 What am I doing wrong? 我究竟做错了什么?
As I am working with some external web page,I cannot use jquery. 由于我正在使用某些外部网页,因此无法使用jquery。 Only Javascript solutions please.
请只使用Javascript解决方案。 Thank You.
谢谢。
getElementsByTagName返回元素集合,如果要获取第一个链接,请使用.getElementsByTagName('a')[0]
As the perent element may contain multiple instances of a same tag, so getElementsByTagName
returns a collection of the elements/nodes 由于perent元素可能包含同一标签的多个实例,因此
getElementsByTagName
返回元素/节点的集合。
So, you have to process it like an array. 因此,您必须像处理数组一样处理它。 Bellow is one of the best way to do this
波纹管是做到这一点的最好方法之一
var holders = document.getElementsByClassName('holder'),
i = holders.length;
while(i--) {
var anchors = holders[i].getElementsByTagName('a');
for (var j = 0; j < anchors.length; j++) {
anchors[j].href="'http://www.google.com";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.