This is a short post. Saving this snippet it for myself for later.
If you ever have a html DOM element with a duplicate ID value, how do you detect the issue? It’s sometimes hard to find/debug until you really understand what has happened.
Taking inspiration from the solution in the following stackoverflow question. http://stackoverflow.com/questions/482763/jquery-to-check-for-duplicate-ids-in-a-dom
I wrote little helper that will alert you early in the development phase if you do something that causes a DOM element with duplicate ID’s.
Place the following script at the bottom of your global master page footer during development, and you will be notified of any issues early in the process.
// Requires: jQuery
(function(document, $){
// little debug helper script to notify us when the
// dom is updated with a contains duplicate ID'd elements
$(document).bind('DOMNodeInserted', function (event) {
var duplicateDomElements = [];
$('[id]').map(function () {
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
duplicateDomElements.push(this.id);
}
});
if (duplicateDomElements.length > 0) {
alert('Recent action duplicated a dom element ID with name(s) [' + duplicateDomElements + ']');
}
});
})(document, jQuery);
How do others typically deal with the issue?