从DOM中删除空元素 [英] remove empty elements from DOM

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

问题描述

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

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

如果我的代码如下所示:

If I have code that looks like this:

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

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

我试过这个: https://www.sitepoint.com/removing-useless-nodes-from-the -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 伪类,用于选择父元素的唯一子元素,删除节点,然后检查父节点是否有。子项,如果没有删除父节点

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天全站免登陆