JS 删除符合条件的 DOM 节点

概述

使用 JavaScript 遍历页面元素,根据内容匹配条件删除指定 DOM 节点。常用于清理页面中不需要的元素或自动化处理。

基础示例

// 遍历并删除内容为"已处理"的整行
document.querySelectorAll("th div i.z em a").forEach((item) => {
    if (item.innerText === "已处理") {
        item.parentNode.parentNode.parentNode.parentNode.parentNode.remove();
    }
});

更优雅的写法

// 使用 closest 替代多层 parentNode
document.querySelectorAll(".status-tag").forEach((item) => {
    if (item.textContent.trim() === "已处理") {
        item.closest("tr")?.remove();  // 删除最近的 tr 行
    }
});

核心方法说明

方法说明兼容性
element.remove()从 DOM 中移除元素自身现代浏览器原生支持
parentNode.removeChild(el)通过父节点删除子节点全部浏览器兼容
element.closest(sel)向上查找最近匹配祖先现代浏览器(推荐)

实用场景

// 1. 删除所有空行
document.querySelectorAll("tr").forEach(row => {
    if (!row.textContent.trim()) row.remove();
});

// 2. 删除指定类名的元素
document.querySelectorAll(".ad-banner, .popup-overlay")
    .forEach(el => el.remove());

// 3. 按属性值删除
document.querySelectorAll("[data-status='inactive']")
    .forEach(el => el.remove());

注意事项

  • 多次 parentNode 链式调用不够稳健,DOM 结构变化容易出错,建议用 closest()
  • remove() 是较新的 API,IE 不支持,需要兼容时用 parentNode.removeChild(el)
  • querySelectorAll 返回的是静态 NodeList,删除元素不会影响遍历

标签: