首页 > 解决方案 > 我怎样才能删除一个

问题描述

也许这是一个基本问题,但我应该强调我对这些事情知之甚少。本质上,在我的页面中,我有类似的内容:

<h2>Some text there</h2>
<h2>Other text there</h2>

我想把它简单地变成:

Some text there
Other text here

我的意思是,本质上,我想删除文本周围的 H2。删除它会非常容易,但不幸的是我只能间接访问代码。有没有办法使用Javascript动态删除它?

标签: javascripthtml

解决方案


您可以遍历所有h2元素并将每个元素替换为元素的文本节点textContent(带有document.createTextNode):

document.querySelectorAll('h2').forEach(e => e.parentNode.replaceChild(document.createTextNode(e.textContent), e))
<h2>Some text there</h2>
<br/>
<h2>Other text there</h2>


推荐阅读