Skip to content

Instantly share code, notes, and snippets.

@Deele
Last active September 4, 2017 14:26
Show Gist options
  • Save Deele/7a831228d8ade3fa139f1b087acd822c to your computer and use it in GitHub Desktop.
Save Deele/7a831228d8ade3fa139f1b087acd822c to your computer and use it in GitHub Desktop.
Monitors document body for duplicate IDs and warns in console when that happens (potential for chrome extension)
(function (window) {
// Based on https://stackoverflow.com/a/14570614/588973
window.observeDOM = (function () {
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
eventListenerSupported = window.addEventListener;
return function (obj, callback) {
if (MutationObserver) {
// define a new observer
var obs = new MutationObserver(function (mutations) {
mutations.every(function(mutation) {
if (mutation.addedNodes.length || mutation.removedNodes.length || mutation.attributeName !== null) {
callback();
return false;
}
return true;
});
});
// have the observer observe foo for changes in children
//noinspection JSCheckFunctionSignatures
obs.observe(obj, {attributes: true, childList: true, subtree: true});
}
else if (eventListenerSupported) {
obj.addEventListener('DOMNodeInserted', callback, false);
obj.addEventListener('DOMNodeRemoved', callback, false);
obj.addEventListener('DOMAttrModified', callback, false);
}
};
})();
// Based on https://stackoverflow.com/a/36129568/588973
window.checkForDuplicateIds = function (container) {
var elms = container.querySelectorAll('*[id]'),
elmsById = {},
i = 0,
len = elms.length,
id;
for (i; i < len; i++) {
if (typeof elmsById[elms[i].id] === 'undefined') {
elmsById[elms[i].id] = [];
}
elmsById[elms[i].id].push(elms[i]);
}
for (id in elmsById) {
if (!elmsById.hasOwnProperty(id)) continue;
if (elmsById[id].length > 1) {
console.warn('Multiple elements with same ID (', id, ') detected', elmsById[id]);
}
}
console.info('checkForDuplicateIds finished');
};
})(top.window);
// Init monitoring
(function (document) {
// Give breathing room before start checking
setTimeout(function () {
// Do initial checking
checkForDuplicateIds(document.body);
// Observer body for repeated checking
observeDOM(
document.body,
function () {
checkForDuplicateIds(document.body);
}
);
}, 2000);
})(document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment