Skip to content

Instantly share code, notes, and snippets.

@CezaryDanielNowak
Last active December 18, 2015 09:49
Show Gist options
  • Save CezaryDanielNowak/5764583 to your computer and use it in GitHub Desktop.
Save CezaryDanielNowak/5764583 to your computer and use it in GitHub Desktop.
Find elements with duplicated ID
(function(field, scope) {
var id,
allIds = {},
elementsWithId = scope.querySelectorAll('[' + field + ']');
Array.prototype.forEach.call(elementsWithId, function(elem) {
if(field.substr(0,5) === 'data-') {
id = elem.dataset[field.substr('5')];
} else {
id = elem[field];
}
allIds[id] = (allIds[id] || 0) + 1;
});
// remove non-duplicated elements from object filled before
for(id in allIds) {
if(allIds[id] < 2) {
delete allIds[id];
}
}
// output
if( JSON.stringify(allIds) === "{}" ) {
console.log('No duplicated IDs in this document.');
return false;
} else {
return allIds;
}
})('id', document);
//use data-reactid for react components
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment