Concisely removing a DOM element if it exists?

Viewed 193

I'm currently writing a browser script (for use in Tampermonkey/Greasemonkey) (and learning JS in the process!), and I have a lot of occurrences like this:

let btn = document.querySelector("#unwantedButton");
if (btn) {
    btn.parentNode.removeChild(btn);
}

That is, I want a certain element to be removed, if it exists.

Is there any way to write this more concisely and elegantly? That would save me a lot of lines in this project, and most importantly, teach me some JS best practice. :-)

Thank you for helping a JS noob!

2 Answers

Rather than rewrite the code in several places, you can put it in a function (and use remove():

function removeIfExists (selector) {
  var x = document.querySelector(selector)
  if (x) x.remove()
}

Then you can call it all over the place:

removeIfExists("#some-unwanted-element")

You can also use it if you have a list of known elements you don't want:

var badElements = [ ".foo", "#bar", "#etc" ]
badElements.forEach(removeIfExists)

You can make it as a function for multiple elements

const removeElements = refs => document.querySelectorAll(refs)
                                .forEach(el=>{if(!!el) el.remove()})

usage :

removeElements('#unwantedButton')

or

removeElements('.foo, #bar, #etc')
Related