Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda