Skip to content

Instantly share code, notes, and snippets.

@antirais
Last active August 29, 2015 13:56
Show Gist options
  • Save antirais/8853684 to your computer and use it in GitHub Desktop.
Save antirais/8853684 to your computer and use it in GitHub Desktop.
Greasemonkey script to look for duplicate HTML id attributes
// ==UserScript==
// @name HTML ID attribute validator
// @description Looks for duplicate IDs in DOM and alerts them
// @namespace all
// @grant none
// @include /^https?://.*/
// @license GPLv3 or any later version (http://www.gnu.org/copyleft/gpl.html)
// @downloadURL https://gist.github.com/antirais/8853684/raw
// @updateURL https://gist.github.com/antirais/8853684/raw
// @version 1.3.3
// @author Anti Räis
// ==/UserScript==
// INSTALL: to install script while viewing the gist in GitHub, click "Raw".
// It should open Greasemonkey confirmation box, then click "Install"
var findDuplicates = function() {
var ids = {};
var duplicates = {};
var nodes = document.querySelectorAll('[id]');
var nodes_count = nodes.length;
var start = Date.now();
if (!nodes_count) return;
while (nodes_count--) {
var node_id = nodes[nodes_count].getAttribute('id');
if (node_id in ids) {
if (node_id in duplicates) {
duplicates[node_id] += 1;
} else {
duplicates[node_id] = 2;
}
} else {
ids[node_id] = node_id;
}
}
console.log("%d attributes scanned in %d ms", nodes.length, (Date.now() - start));
if (Object.getOwnPropertyNames(duplicates).length) {
alert("Duplicates: " + JSON.stringify(duplicates, null, 4));
}
}
document.addEventListener('DOMContentLoaded', findDuplicates, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment