Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
Checking value of child that doesn't exist?

My html code contains a <ul id="users"></ul>, which is then populated dynamically with JS code

const li = document.createElement("li");
li.appendChild(document.createTextNode(`${nameInput.value} : ${emailInput.value}`)

I added a button in the html code to delete all users in that <ul>,as such: <button class="btn" id="del-user-list" onClick="deleteUserList()">Delete User List</button>.

My deleteUserList function in the JS code looks like this:

function deleteUserList() {
  while (userList.firstChild != "") {
    userList.firstChild.remove();
  }
}

This works on the surface, however I realize that after the last child, my function will check once again for the value of a child that doesn't exist. I remember from studying C and playing with linked lists that you don't want to dereference a pointer that points to null.

Sure enough, when I look at the console I get Uncaught TypeError: Cannot read properties of null (reading 'remove') at deleteUserList (main.js:31:25) at HTMLButtonElement.onclick ((index):29:77)

Is this a problem and what can I do about it? I just started playing with Javascript and don't have a good sense of how those things work right now.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Instead of comparing userList.firstChild to an empty string, you should compare it against null or omit the comparison operator entirely:

while (userList.firstChild != null)
// or
while (userList.firstChild) 

The latter one works because converting null to a boolean value returns false

null != '' will always be true because userList.firstChild will never be an empty string anyway. It will either be a DOM node or null.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda