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

check for duplicate before appendChild

const pickNewUl = document.getElementById("ullist1");     
var createLi = document.createElement("li");
                            createLi.id = listItems[i].id;
                            createLi.classList.add(pickNewUlsl);
                            createLi.innerHTML = listItems[i].textContent; 
                            createLi.innerHTML += "<a onclick='remove(this)' class='removebtn'>X</a>";
pickNewUl.appendChild(createLi);

What I need to check in above code is: I want to check if there are any same id LI exists or not, if not then only it should append, otherwise it will not append.

pickNewUl is a UL list

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

>Solution :

You can find for any element inside element with .querySelectorAll as below.

if (pickNewUl.querySelectorAll('#' + listItems[i].id).length === 0) {
    // Add element    
}

Reference : https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Your complete code should be like below.

const pickNewUl = document.getElementById("ullist1"); 
if (pickNewUl.querySelectorAll('#' + listItems[i].id).length === 0) {   
    var createLi = document.createElement("li");
    createLi.id = listItems[i].id;
    createLi.classList.add(pickNewUlsl);
    createLi.innerHTML = listItems[i].textContent; 
    createLi.innerHTML += "<a onclick='remove(this)' class='removebtn'>X</a>";
    pickNewUl.appendChild(createLi);
}
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