首页 > 解决方案 > 删除 p 标签的内容

问题描述

有没有办法p使用 JavaScript 从标签中删除某些内容?

如果我有 5 个p带有字符串First note的标签Fifth note,我想循环使用querySelectorAll,然后使用该功能从标签remove中删除字符串。notep

这是我管理的程度,但我缺乏在p标签中指定要删除的字符串的功能:

const pTag = document.querySelectorAll('p')
pTag.forEach(function (p) {
    p.remove()
})

标签: javascripthtml

解决方案


您不能使用该remove()方法仅删除部分字符串。您可以改用该replace()方法:

const pTag = document.querySelectorAll('p');
pTag.forEach(function(p) {
  p.innerHTML = p.innerHTML.replace('note', '');
});
<p>This is the first note</p>
<p>This is the second note</p>
<p>This is the third note</p>
<p>This is the fourth note</p>
<p>This is the fifth note</p>


推荐阅读