-3

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.

  • 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 Answers2

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;
    
}
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