9
Dec
2010
Duplicate DOM elements with the same ID
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?
I have a similar function except I have also decided (recently) to bind DOMAttrModified event as well. I guess it is not entirely required since most of the duplicate nodes will come from additions or replacements to the document.
The theory behind this motive goes something like: never trust anyone.
So adding that extra event binding would allow catch whenever I do naughty things like $(‘a:get(2)’).attr(‘id’, $(‘a:first’).attr(‘id’));