Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if there are duplicate element ID on a page in array or list?

I just want to check if there are duplicate element ID 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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading