0

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.

Valli69
  • 8,856
  • 4
  • 23
  • 29

3 Answers3

1

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 :)

Bill
  • 25,119
  • 8
  • 94
  • 125
  • Read this http://meta.stackexchange.com/questions/87678/discouraging-w3schools-as-a-resource – Ilia Frenkel Apr 13 '12 at 05:14
  • 2
    @IliaFrenkel, the problem is that I find w3schools to be seriously lacking when it comes to the quality of information. In many cases it will be partially correct, but have serious issues in example material. It's much better to just assume w3schools has it all wrong and [reference the specification](http://www.whatwg.org/specs/web-apps/current-work/multipage/) instead. – zzzzBov Apr 13 '12 at 05:17
  • @zzzzBov I don't like w3schools neither, but making an assumption that the whole site is wrong is a little ambitious. – Ilia Frenkel Apr 13 '12 at 05:20
  • @IliaFrenkel, a broken watch is correct twice a day. Doesn't mean I'm going to wear it. – zzzzBov Apr 13 '12 at 05:22
0

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.

Community
  • 1
  • 1
Ilia Frenkel
  • 1,969
  • 13
  • 19
0

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.

Kevin C. Krinke
  • 421
  • 4
  • 5