Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
}
about 4 years ago · Santiago Trujillo Report

0

You can just wrap you code inside an if:

// the same as before but using pickNewUl instead of document
if (!pickNewUl.getElementById(listItems[i].id)) {
  const createLi = document.createElement("li");
  ...
  pickNewUl.appendChild(createLi);
}

Btw, I suggest to use a different approach excluding duplicated id:

// The string into querySelector method is a template string.
if (!pickNewUl.querySelector(`[data-item-id="${listItems[i].id}"]`)) {
  const createLi = document.createElement("li");
  createLi.dataset.itemId=listItems[i].id;
  ...
  pickNewUl.appendChild(createLi);
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!