Reputation: 3099
Something goes wrong when I try outputting the elements from document.links
array. Is the cause coming from wrong implementation of for-loop ??. Have a look :
// below is the HMTL
<p>
<a name="one" href="http://www.kaskus.co.id">Kaskus</a><br>
<a name="two" href="http://www.bola.net">Bola-net</a><br>
<a name="three" href="http://www.kompas.co.id">Kompas</a><br>
</p>
....................
....................
.....................
// below is the JS
<script type="text/javascript">
for( i in document.links){
document.write("<br>"+document.links[i].text);
}
</script>
And the output is :
Kaskus
Bola-net
Kompas
undefined
<-- this is even funny,what is this ?
Kaskus
Bola-net
Kompas
undefined
undefined
What probably causes such undefined ?
Upvotes: 0
Views: 239
Reputation: 943614
The document.links
object gives you multiple ways to access the links in the document.
First, like an array, it has a numerical index for each one as well as a length (which is what you are complaining about with "this is even funny,what is this", numbers don't have a text property). Then, it lets you access them by name (so you get a second entry for each link). It also has a couple of functions dangling off it.
Change your code to:
document.write("<br>"+i+" : " +document.links[i].text);
And you'll see all the property names you are iterating through and it will make sense.
Don't use a for in
loop, use a traditional array loop.
for(var i = 0; i < document.links.length; i++){
document.write("<br>"+document.links[i].text);
}
You should have just console.log(document.links)
, then you could have seen what all the properties you were dealing with were.
Upvotes: 1