Reputation: 9892
I'm new to javascript programming. I have found below example while practicing javascript.
<html>
<head>
<script type="text/javascript">
function changeTabIndex()
{
document.getElementById('1').tabIndex="3"
document.getElementById('2').tabIndex="2"
document.getElementById('3').tabIndex="1"
}
</script>
</head>
<body>
<p><a id="1" href="http://www.w3schools.com">1</a></p>
<p><a id="2" href="http://www.w3schools.com">2</a></p>
<p><a id="3" href="http://www.w3schools.com">3</a></p>
<input type="button" onclick="changeTabIndex()"
value="Change TabIndex" />
</body>
</html>
What's my doubt is, naming conventions for id attribute must start with an alphabet followed by numbers and underscore. But in this example even though they used numbers as id's the code working fine.Then what is the need of following naming conventions. It seems to be simple but anyone please clarify it.
Upvotes: 0
Views: 92
Reputation: 421
getElementById() looks for a token value in the ID attribute, which can actually be either a "NAME" or a "NUMBER". I have yet to see the part of the spec that states this exactly but it's how I've interpreted the doc based on examples like yours. Both conventions work in practice, however, I've never liked using just a number ID. Things like jQuery sorta breakdown in usefulness with $(#42) written in the code.
Upvotes: 0
Reputation: 1977
According to this What are valid values for the id attribute in HTML? in HTML5 an id must contain at least one character and may not contain any space characters. I'm guessing that your example may not work in older browsers.
Upvotes: 0
Reputation: 25555
Most people would recommend that you don't rely on www.w3schools.com for information regarding Javascript. There are lots of errors in their documentation and their examples. A better source of information is the actual W3C reference docs. Information on IDs can be found at http://www.w3.org/TR/html401/struct/global.html#h-7.5.2. In this particular instance, your browser implementation simply isn't following the spec :)
Upvotes: 1