【问题标题】:Remove element with attribute JS [duplicate]删除具有属性 JS 的元素 [重复]
【发布时间】:2021-07-26 17:37:49
【问题描述】:

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

我试过了:

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

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

【问题讨论】:

    标签: javascript jquery select attributes


    【解决方案1】:

    querySelectorAll() 返回集合,你应该遍历它们并一个一个删除:

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

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

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

    【讨论】:

    • 来一个接近投票而不是另一个 "... 返回一个集合" 答案怎么样?
    猜你喜欢
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多