Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery to check for duplicate ids in a DOM

Tags:

jquery

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.

like image 930
Simon_Weaver Avatar asked Jan 27 '09 09:01

Simon_Weaver


4 Answers

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);
});
like image 54
sunsean Avatar answered Nov 19 '22 20:11

sunsean


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');
})();
like image 28
Sjoerd Avatar answered Nov 19 '22 21:11

Sjoerd


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);
            }
        }
    }
}());
like image 14
AutoSponge Avatar answered Nov 19 '22 19:11

AutoSponge


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

like image 12
Ionuț G. Stan Avatar answered Nov 19 '22 21:11

Ionuț G. Stan