script to check for duplicated ID's

script to check for duplicated ID's

I often see people use duplicated ID's in their html, and this is a common cause for some issues posted on this forum. To help, I wrote this javascript to check and report duplicated ID's. Try to run it and see how it works.
 
  1. <html>
  2. <head>
  3.         <script type="text/javascript" src="jquery-1.4.2.js"></script>
  4.         <script type="text/javascript">
  5.                 $(document).ready(function() {
  6.                         var idDictionary = {};
  7.                         $('[id]').each(function() {
  8.                                 idDictionary[this.id] == undefined ? idDictionary[this.id] = 1 : idDictionary[this.id] ++;
  9.                         });
  10.                         for (id in idDictionary) {
  11.                                 if (idDictionary[id] > 1) {
  12.                                         alert("ID " + id + " was used for " + (idDictionary[id]) + " times");
  13.                                 }
  14.                         }
  15.                 });
  16.         </script>
  17. </head>
  18. <body>
  19. <span id="a">1</span>
  20. <span id="b">1</span>
  21. <span id="a">1</span>
  22. <span id="c">1</span>
  23. <span id="d">1</span>
  24. <span id="c">1</span>
  25. </body>
  26. </head>