Skip to content
Advertisement

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?

Advertisement

Answer

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

Advertisement