This causes an error:
JavaScript
x
2
1
document.querySelector('#element-that-does-not-exist').remove()
2
The way I fix it:
JavaScript
1
5
1
let el = document.querySelector('#element-that-does-not-exist')
2
if (el) {
3
el.remove()
4
}
5
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
1
2
1
document.querySelector('#element-that-does-not-exist')?.remove()
2
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