Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript document.anchors.length returning 1 in firefox

I am trying to run through a list of 6 anchors in a page using javascript to do some operations on them. However, the loop is not getting executed because anchors.length is return 1. The following is my code snippet:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function load()
{
alert(document.anchors.length);
for (i = 0; i <= document.anchors.length; i++)
    {
        alert(document.anchors[i].innerHTML);
    }
}
</script>
</head>
<body onload="load()">
<div>        
<ul>
<a id="sectionlinks" href="page1.html">link 1</a></li>
<a id="sectionlinks" href="page2.html">link 2</a></li>
<a id="sectionlinks" href="page3.html">link 3</a></li>
<a id="sectionlinks" href="page4.html">link 4</a></li>
<a id="sectionlinks" href="page5.html">link 5</a></li>
<a id="sectionlinks" href="page6.html">link 6</a></li>
<ul>
</div>
</body>
</html>

This is working fine in IE9. But in Firefox and Chrome, it is saying that the count is equal to 1. Would be great if someone can point me to what I have missed here.

As you might have guessed, I am a newbie to JS and am just learning it.

like image 585
Karthick S Avatar asked May 14 '26 18:05

Karthick S


1 Answers

At least, you're learning the correct way, keep going!

What you've done wrong is that document.anchors refers to anchor links (old anchor links using the name attribute), not normal links. For example, the following is an anchor:

<a name="tab"></a>

And the following is a link:

<a href="/some/link"></a>

The links are in the document.links HTMLCollection, so you can use document.links.length.

If you want to get all the <a> elements, no matter what's in their attribute, you can use document.getElementsByTagName( 'a' ).length.

like image 198
Florian Margaine Avatar answered May 17 '26 08:05

Florian Margaine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!