Javascript - getElementById fails if anchor also has a name attribute
-
18-09-2019 - |
Question
I'm running into an odd failure. It seems that if I have both an ID and NAME attribute on an anchor element, document.getElementById fails. If I remove the NAME, it works. I'm seeing this in Firefox 3.5(latest) but haven't checked other browsers yet.
Is this a bug or intentional?
Solution
I've never heard of such a bug, so I attempted to reproduce it and failed. This suggests that you have misdiagnosed the problem, or at least haven't provided enough information about it.
I tested with Firefox 3.5 and the following code.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<title>Test of getElementById with named anchors</title>
<h1>Test of getElementById with named anchors</h1>
<h2><a name="one" id="one">First section</a></h2>
<p>The quick brown fox</p>
<h2><a name="two" id="second">Second section</a></h2>
<p>The quick brown fox</p>
<script type="text/javascript">
if (document.getElementById('one')) {
document.write("<p>First section found - id matches name<\/p>");
}
if (document.getElementById('second')) {
document.write("<p>Second section found - id does not match name<\/p>");
}
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow