Just a small problem regarding javscript BOM question

Posted by caramel1991 on Stack Overflow See other posts from Stack Overflow or by caramel1991
Published on 2010-05-23T07:59:58Z Indexed on 2010/05/23 8:00 UTC
Read the original article Hit count: 237

Filed under:

The question is this:

Create a page with a number of links. Then write code that fires on the window onload event, displaying the href of each of the links on the page.

And this is my solution

<html>
<body language="Javascript" onload="displayLink()">
<a href="http://www.google.com/">First link</a>
<a href="http://www.yahoo.com/">Second link</a>
<a href="http://www.msn.com/">Third link</a>

<script type="text/javascript" language="Javascript">
function displayLink()
{
 for(var i = 0;document.links[i];i++)
 {
 alert(document.links[i].href);
 }
}
</script>

</body>
</html>

This is the answer provided by the book

<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
function displayLinks()
{
 var linksCounter;
 for (linksCounter = 0; linksCounter < document.links.length; linksCounter++)
 {
  alert(document.links[linksCounter].href);
 }
}
</script>
</head>
<body onload=”displayLinks()”>
<A href=”link0.htm” >Link 0</A>
<A href=”link1.htm”>Link 2</A>
<A href=”link2.htm”>Link 2</A>
</body>
</html>

Before I get into the javascript tutorial on how to check user browser version or model,I was using the same method as the example,by acessing the length property of the links array for the loop,but after I read through the tutorial,I find out that I can also use this alternative ways,by using the method that the test condition will evalute to true only if the document.links[i] return a valid value,so does my code is written using the valid method??If it's not,any comment regarding how to write a better code??Correct me if I'm wrong,I heard some of the people say "a good code is not evaluate solely on whether it works or not,but in terms of speed,the ability to comprehend the code,and could posssibly let others to understand the code easily".Is is true??

© Stack Overflow or respective owner

Related posts about JavaScript