views:

70

answers:

3

Save the following in a file (eg. file.htm) and it works => prints out "3". But if I uncomment the line 'document.write("Hello: ");' it doesn't work anymore (prints out "0"). Anyone knows why?

<html>
<head>
<script language="JavaScript" type="text/javascript">
function display() {
    //document.write("Hello: ");
    document.write(document.links.length + "<br>");
}
</script>
</head>
<body onload="display()">

<A href="link0.htm">Link 0</A>
<A href="link1.htm">Link 1</A>
<A href="link2.htm">Link 2</A>

</body>
</html>
+1  A: 

First, don't use document.write() to "display" your output. If this is just a test, use the alert() method. document.write() is only supposed to be used while the page is loading. Once the stream is closed and the document is loaded, document.write() will have unpredictable results.

Second, instead of using document.links, try using document.getElementsByTagName("A"). That will give you an array of all the anchor tags in the document.

Robusto
It may be useful for other tags, but how do I count the num of tags with "___" in a document?
yeeen
You didn't ask that question. You asked about links (<a></a>), otherwise known as "anchor" tags, and your example showed exactly those tags and nothing more.
Robusto
My example exactly counts the number of anchor tags.
yeeen
+6  A: 

In Chrome I observe this behaviour, and most other browsers probably too. The reason is as follows:

Without the first document.write, it works as expected. Nothing special here.

But when you include the first document.write it overwrites the entire contents of the document, so then there aren't any links left. The second document.write reports correctly that there are 0 links in the document.

Mark Byers
Was typing this actually! Good job
Aviator
Pretty much, don't use document.write. Ever.
Matchu
I tried it in IE, Firefox and Chrome. I think u are correct and ur explanation is very clear. Thanks!
yeeen
A: 

Because when you call document.write the first time, it removes all links from the DOM. It replaces the entire innerHTML of document.body with "Hello: ".

You should never use document.write anyway.

Josh Stodola