Check for duplicate 'id' values in a HTML page

15,458

Solution 1

The W3C's validator tool will report duplicate IDs. To test your code:

  1. Copy the generated source code to your clipboard.
  2. Visit http://validator.w3.org/#validate_by_input
  3. Paste your markup into the box and hit 'Check'.

You can test it with the following code if you wish:

<!doctype html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <div id="test">Test div</div>
        <div id="test">Test div 2</div>
    </body>
</html>

This produces the following error:

enter image description here

Solution 2

Run this code on your browser’s JavaScript console:-

(function findDuplicateIds() {
    var ids = {};
    var all = document.all || document.getElementsByTagName("*");
    for (var i = 0, l = all.length; i < l; i++) {
        var id = all[i].id;
        if (id) {
            if (ids[id]) {
                console.log("Duplicate id: #" + id);
            } else {
                ids[id] = 1;
            }
        }
    }
})();

Solution 3

  1. http://validator.w3.org/check

  2. If you have Web Developer Toolbar installed, you can use it to contact the above service directly from browser: Tools -> Validate Local HTML

  3. Some developer tools (like PhpStorm/WebStorm) automatically perform such validation.

Solution 4

Use the W3C Validator. It will tell you if there are duplicated ids.
If your site is not online, use Opera. They have a nice feature that uploads the page in order to validate it.

  • Right click on the page
  • Validate

enter image description here enter image description here

Share:
15,458

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin over 1 year

    I am developing a web application and I would like to check for duplicate id values in a HTML page. I am running the application on my local machine.

    There is a way to do that?

    P.S.: I am using Firefox and Firebug.

  • Eduardo Valladares
    Eduardo Valladares about 5 years
    Is there a way to check for duplicates of a particular id that avoids iterating through all elements?
  • Eduardo Valladares
    Eduardo Valladares about 5 years
    To answer my own question, this appears to work: document.querySelectorAll("[id='test']")
  • BeNice
    BeNice over 4 years
    all is now deprecated. Care to modify? Tweaked this and VERY helpful. Somehow I have turned off duplicate id checking in my IDE and this saved me big time. Thanks