JQuery to check for duplicate ids in a DOM

I'm writing applications with ASP.NET MVC. In contrast to traditional ASP.NET you're a lot more responsible for creating all the ids in your generated page. ASP.NET would give you nasty, but unique ids.

I'd like to add a quick little jQuery script to check my document for duplicate ids. They may be ids for DIVS, images, checkboxes, buttons etc.

<div id="pnlMain"> My main panel </div>
<div id="pnlMain"> Oops we accidentally used the same ID </div> 

I'm looking for a set and forget type utility that'll just warn me when I do something careless.

Yes i'd be using this only during testing, and alternatives (such as firebug plugins) are welcome too.


Solution 1:

The following will log a warning to the console:

// Warning Duplicate IDs
$('[id]').each(function(){
  var ids = $('[id="'+this.id+'"]');
  if(ids.length>1 && ids[0]==this)
    console.warn('Multiple IDs #'+this.id);
});

Solution 2:

This version is somewhat faster, and you can copy it to a bookmark button to make it a bookmarklet.

javascript:(function () {
  var ids = {};
  var found = false;
  $('[id]').each(function() {
    if (this.id && ids[this.id]) {
      found = true;
      console.warn('Duplicate ID #'+this.id);
    }
    ids[this.id] = 1;
  });
  if (!found) console.log('No duplicate IDs found');
})();

Solution 3:

I have a big page, so that script runs too slow to finish (multiple "continue script" messages). This works fine.

(function () {
    var elms = document.getElementsByTagName("*"), i, len, ids = {}, id;
    for (i = 0, len = elms.length; i < len; i += 1) {
        id = elms[i].id || null;
        if (id) {
            ids[id] =  ids.hasOwnProperty(id) ? ids[id] +=1 : 0;
        }
    }
    for (id in ids) {
        if (ids.hasOwnProperty(id)) {
            if (ids[id]) {
                console.warn("Multiple IDs #" + id);
            }
        }
    }
}());

Solution 4:

You should try HTML Validator (Firefox extension). It'll definitely tell you the page has duplicate ids and much more.