【问题标题】:Remove empty headings that contain additional empty html tags删除包含额外空 html 标记的空标题
【发布时间】:2022-10-14 21:54:54
【问题描述】:

我的代码中有一个脚本来删除所有空标题标签,因此屏幕阅读器不会读取它们:

    $("h1:empty, h2:empty, h3:empty, h4:empty, h5:empty, h6:empty").replaceWith('');

但它没有选择包含额外空 html 的标题标签,如 <h2><strong></strong></h2>

我怎样才能删除这些?

【问题讨论】:

  • 为什么选择 JavaScript?如果页面是静态的,那么只需删除那些空标题。如果它是动态生成的,则修复那些空标题的来源。
  • 它来自 CMS,不幸的是,删除所有意外添加的内容太耗时了。

标签: javascript html jquery


【解决方案1】:
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>

【讨论】:

  • 为什么.querySelector().querySelectorAll()?为什么只有第一个&lt;div&gt;
【解决方案2】:

您需要使用text() 属性。

$('h1, h2, h3, h4, h5, h6').each(function(){
    if( $(this).text().trim() === '' )
        $(this).remove();
});

【讨论】:

    【解决方案3】:

    以下是使用 vanilla JavaScript 执行此操作的方法:

    document.querySelectorAll('h1, h2, h3, h4, h5, h6').forEach(el =>
      !el.textContent.replace(/(s|
    )+/g, '') && el.remove());
    <h1>abc</h1>
    <h2>def</h2>
    <h3>
      <strong>
      
      </strong>
    </h3>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 2015-09-01
      • 2020-05-12
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      相关资源
      最近更新 更多