问题描述
我目前正在编写一个浏览器脚本(用于在 Tampermonkey/Greasemonkey 中使用)(并在此过程中学习 JS!),并且我很多 出现了像这样:
let btn = document.querySelector("#unwantedButton");
if (btn) {
btn.parentNode.removeChild(btn);
}
也就是说,我想删除某个元素(如果存在)。
有没有什么办法可以写得更简洁优雅?这将为我在这个项目中节省很多行,最重要的是,教我一些 JS 最佳实践。 :-)
感谢您帮助 JS 菜鸟!
解决方法
与其在多个地方重写代码,不如将其放在一个函数中(并使用 remove()
:
function removeIfExists (selector) {
var x = document.querySelector(selector)
if (x) x.remove()
}
然后你可以到处调用它:
removeIfExists("#some-unwanted-element")
如果您有不想要的已知元素列表,也可以使用它:
var badElements = [ ".foo","#bar","#etc" ]
badElements.forEach(removeIfExists)
,
您可以将其设为多个元素的函数
const removeElements = refs => document.querySelectorAll(refs)
.forEach(el=>{if(!!el) el.remove()})
用法:
removeElements('#unwantedButton')
或
removeElements('.foo,#bar,#etc')