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

389
Vistas
Best way to prevent an error when calling remove() on a non-existing element

This causes an error:

document.querySelector('#element-that-does-not-exist').remove()

The way I fix it:

let el = document.querySelector('#element-that-does-not-exist')
if (el) {
  el.remove()
}

My question - is there a more elegant way to prevent an error? One line of code preferably?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can just use the safe navigation operator:

document.querySelector('#element-that-does-not-exist')?.remove()

In this way, if querySelector returns null, remove() won't be called.

If you are not using a transpiler like Babel or Webpack, you may be interested in knowing the compatibility table: https://caniuse.com/mdn-javascript_operators_optional_chaining

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