Skip to content

Instantly share code, notes, and snippets.

@butchi
Last active November 8, 2023 00:06
Show Gist options
  • Save butchi/bdb2b661d6a93b436a43 to your computer and use it in GitHub Desktop.
Save butchi/bdb2b661d6a93b436a43 to your computer and use it in GitHub Desktop.
DOM上のIDの重複を検出する ref: http://qiita.com/butchi_y/items/8e1312a47826e5ca95a2
(function(){
var idArr=[];
var duplicateIdArr = [];
[].forEach.call(document.querySelectorAll('[id]'), function(elm){
var id = elm.getAttribute('id');
if(idArr.indexOf(id) !== -1) {
duplicateIdArr.push(id);
} else {
idArr.push(id);
}
});
if(duplicateIdArr.length > 0) {
console.log('IDの重複があります:', duplicateIdArr);
} else {
console.log('IDの重複はありません。');
}
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>has only unique ids</title>
</head>
<body>
<div id="aaa"></div>
<div id="bbb"></div>
<div id="ccc"></div>
<p id="ddd"></p>
<div id="eee"></div>
</body>
</html>
IDの重複はありません。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>has duplicate ids</title>
</head>
<body>
<div id="aaa"></div>
<div id="bbb"></div>
<div id="ccc"></div>
<p id="aaa"></p>
<div id="bbb"></div>
</body>
</html>
IDの重複があります: ["aaa", "bbb"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment