Last active
August 3, 2025 16:32
-
-
Save TracyGJG/cbb198119ae89c8bbe8f1105a241480f to your computer and use it in GitHub Desktop.
Function to detect and report elements with duplicate Ids
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Duplicate Ids</title> | |
</head> | |
<body> | |
<div id="$m1"> | |
<p id="p1"></p> | |
<p id="p2"></p> | |
<p id="p3"></p> | |
<p id="p4"></p> | |
</div> | |
<div id="$m2"> | |
<p id="p1"></p> | |
<p id="p2"></p> | |
<p id="p1"></p> | |
<p id="p3"></p> | |
<p id="p1"></p> | |
<p id="p3"></p> | |
</div> | |
<script> | |
function checkForDuplicateElementIds(target = document.body) { | |
const elementsWithIds = [...target.querySelectorAll(`[id]`)].map( | |
(_) => _.id | |
); | |
const uniqueIds = [...new Set(elementsWithIds)]; | |
const duplicateIds = uniqueIds.filter( | |
(id) => elementsWithIds.filter((elId) => elId === id).length > 1 | |
); | |
if (duplicateIds.length) { | |
console.error( | |
`Error, there are elements with duplicate ids:`, | |
duplicateIds.join(', ') | |
); | |
} | |
} | |
checkForDuplicateElementIds($m1); | |
checkForDuplicateElementIds($m2); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment