简体   繁体   中英

document.write inside for loops

I have the following HTML document

<html>
<script>
        function explode() {
                pp = document.getElementsByTagName("a");
                for(i=0;i<pp.length;i++) {
                    document.write(pp[i].href);
                }
        }
</script>

<body>
 <a href="http://google.com">Google</a>
 <a href="http://yahoo.com">Yahoo</a>
 <button onclick="explode()">Explode</button>
<body>

</html>

When executed I expect all the hyperlinks printed on my window, but I get only the first one. Can someone explain this

Update I am convinced by the answer that document.write will reset the page contents, but if it is that so then, I already the list of objects in the variable pp and by the end of the for loop I should get the LAST element, why the first element ?

document.write - will clear your browser at first time when he meets document.write !

You have to aggregate the values.

Do this

  function explode() {
            pp = document.getElementsByTagName("a");
            var a='';
            for(i=0;i<pp.length;i++) {
              a+=pp[i].href
            }
       document.write(a);
    }

http://jsbin.com/buzexuce/2/edit

To illustrate on the other direction :

look what happens here : 

 <a href="http://google.com">Google</a>
 <a href="http://yahoo.com">Yahoo</a>
 <button onclick="explode()">Explode</button>

  <script>
    var  pp = document.getElementsByTagName("a");
                for(i=0;i<pp.length;i++) 
                { document.write(i);}
    </script>

在此处输入图片说明

(before dom ready - everything is fine as expected).

If you start writing to the document after it has been completely loaded, you will implicitly open a new document and replace the current document. You can use document.write to add to the document while it is loading (ie in scripts tags inline in the code), but once the document is complete, using document.write will implicitly call document.open to create a new document to write to.

The list of elements that you get from the getElementByTagName method returns a live list, which is updated when elements are added to or removed from the DOM. When you have written the first item to the document the list is empty, as there aren't any matching elements in the document any more.

它应该是:

document.write(pp[i].href);

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