问题
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.
回答1:
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
.
回答2:
See the note in the MDN documentation:
For reasons of backwards compatibility, the returned set of anchors only contains those anchors created with the name attribute, not those created with the id attribute.
The property is designed to find anchors to link to, not from.
Use document.getElementsByTagName('a')
to get a collection of <a>
elements or document.links to get those and <area>
s
来源:https://stackoverflow.com/questions/10945536/javascript-document-anchors-length-returning-1-in-firefox