Skip to content
Advertisement

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

This causes an error:

JavaScript

The way I fix it:

JavaScript

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:

JavaScript

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