JQuery to check for duplicate ids in a DOM
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);
});
You should try HTML Validator (Firefox extension). It'll definitely tell you the page has duplicate ids and much more.
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);
}
}
}
}());
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');
})();