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.
- <html>
- <head>
- <script type="text/javascript" src="jquery-1.4.2.js"></script>
- <script type="text/javascript">
- $(document).ready(function() {
- var idDictionary = {};
- $('[id]').each(function() {
- idDictionary[this.id] == undefined ? idDictionary[this.id] = 1 : idDictionary[this.id] ++;
- });
- for (id in idDictionary) {
- if (idDictionary[id] > 1) {
- alert("ID " + id + " was used for " + (idDictionary[id]) + " times");
- }
- }
- });
- </script>
- </head>
- <body>
- <span id="a">1</span>
- <span id="b">1</span>
- <span id="a">1</span>
- <span id="c">1</span>
- <span id="d">1</span>
- <span id="c">1</span>
- </body>
- </head>