I just want to check if there are duplicate element ID with duplicate length in a list or array in my webpage in JavaScript. Besides from being suspicious if I really but a duplicate element ID in the page.
Asked
Active
Viewed 190 times
-3
-
Does this answer your question? [Html javascript code that check the duplicate id](https://stackoverflow.com/questions/13917825/html-javascript-code-that-check-the-duplicate-id) – Sercan Aug 07 '22 at 02:15
2 Answers
0
It a bit brute force, but here's how I do it. Test the code here!
function checkSameElementID(){
var elementz = document.querySelectorAll('*[id]');
var elementh = [];
var elementsm = [];
var elementsmc = [];
var elementrv = [];
elementz.forEach((elementx, index) => {
var eleName = elementx.getAttribute("id");
if(elementh.includes(eleName)){
if(!elementsm.includes(eleName)){
elementsm.push(eleName);
elementsmc.push(2);
}
else{
var posx = elementsm.indexOf(eleName);
var updlengthx = elementsmc[posx] + 1;
elementsmc[posx] = updlengthx;
}
}
elementh.push(eleName);
});
elementsm.forEach((elementx, index) => {
var lengthx = elementsmc[index];
var namex = String(elementx);
elementrv.push({'id': namex, 'length': lengthx});
});
if(elementsm.length == 0){
elementrv = "No Element ID duplicates!";
}
return elementrv;
}

Jerwin Dela Cruz
- 16
- 1
-
Thanks for this, it not only check one id at a time but it check all ID in the page. – Valora Sphynx Aug 07 '22 at 02:17
0
Take the ID that you want to check. For example, if it's foo
- with the selector string [id="foo"]
, you'll match all elements on the page with the foo
id - then you can see if the first element is the same as the last.
const foos = document.querySelectorAll('[id="foo"]');
if (foos[foos.length - 1] !== foos[0]) {
console.log('Dupe found');
}
<div id="foo">1</div>
<div id="foo">2</div>
But on a decently-structured page, such duplicate IDs should not have a possibility of existing; it's invalid HTML.

CertainPerformance
- 356,069
- 52
- 309
- 320