Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

386
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!