Check for duplicate 'id' values in a HTML page
The W3C's validator tool will report duplicate IDs. To test your code:
- Copy the generated source code to your clipboard.
- Visit http://validator.w3.org/#validate_by_input
- Paste your markup into the box and hit 'Check'.
You can test it with the following code if you wish:
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="test">Test div</div>
<div id="test">Test div 2</div>
</body>
</html>
This produces the following error:
http://validator.w3.org/check
If you have Web Developer Toolbar installed, you can use it to contact the above service directly from browser: Tools -> Validate Local HTML
Some developer tools (like PhpStorm/WebStorm) automatically perform such validation.
Run this code on your browser’s JavaScript console:-
(function findDuplicateIds() {
var ids = {};
var all = document.all || document.getElementsByTagName("*");
for (var i = 0, l = all.length; i < l; i++) {
var id = all[i].id;
if (id) {
if (ids[id]) {
console.log("Duplicate id: #" + id);
} else {
ids[id] = 1;
}
}
}
})();