删除具有JS属性的元素



我想用data-loc-id='2218'删除元素。我该怎么做?

我试过这个:

document.querySelectorAll(`[data-loc-id='2218']`).remove();

错误:Uncaught TypeError: document.querySelectorAll(...).remove is not a function

querySelectorAll()返回集合,您应该循环遍历它们并逐个移除:

document.querySelectorAll(`[data-loc-id='2218']`).forEach(el => el.remove());

OR:如果您有一个具有属性值的元素,则使用querySelector(),返回文档中第一个匹配的元素:

document.querySelector(`[data-loc-id='2218']`).remove();

最新更新