简体   繁体   中英

Can't select child elements using getElementsByTagName

Here is the HTML code:

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

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. What am I doing wrong?

As I am working with some external web page,I cannot use jquery. Only Javascript solutions please. 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

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";
    }

}

Demo Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM