从DOM中删除空节点元素 [英] Remove empty node elements from DOM

查看:48
本文介绍了从DOM中删除空节点元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在没有jQuery的情况下从dom中识别和删除空元素的最佳方法是什么?

What is the best way to identify and remove empty elements from the dom WITHOUT jQuery?

如果我有如下代码:

<div>
    <div>
        <p></p>
    </div>
    <div>
        <p>Some content</p>
    </div>
</div>

摆脱空的< p> < div> 的最佳方法是什么?

What is the best way to get rid of both the empty <p> and <div>?

我尝试了此操作: https://www.sitepoint.com/remove-useless-nodes-from-dom/,但由于某种原因,它清除了我跨度中的所有空间.

I tried this: https://www.sitepoint.com/removing-useless-nodes-from-the-dom/ but for some reason it cleaned out all of the spaces in my spans.

推荐答案

您可以使用:only-child 伪类来选择作为父元素唯一子元素的元素,删除该节点,然后检查父节点是否具有 .children ,如果没有,请删除父节点

You can use :only-child pseudo class to select elements which are the only child of a parent element, remove the node, then check if the parent node has .children, if not remove the parent node

let nodes = document.querySelector("div")
            .querySelectorAll(":only-child");

nodes.forEach(node => {
  if (!node.childNodes.length) {
    let parent = node.parentNode;
    node.parentNode.removeChild(node);
    if (!parent.children.length) {
      parent.parentNode.removeChild(parent)
    }
  }
});

console.log(document.querySelector("div").innerHTML);

<div>
    <div>
        <p></p>
    </div>
    <div>
        <p>Some content</p>
    </div>
</div>

这篇关于从DOM中删除空节点元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆