我正在尝试使用JavaScript删除HTML元素<p><br></p>
const blog = document.getElementById('blog');
const postNode = document.createElement('div');
postNode.innerHTML = postNode.innerHTML.replace('<p><br></p>', '');
blog.appendChild(postNode);
但是,replace
似乎并没有摆脱innerHTML
中的字符串。我认为是因为当前输出是
<h2>This is a heading two</h2><p>This is a paragraph</p><p><br></p><p>This is a paragraph with a <strong>bold</strong> an <em>italic</em> and an <u>underscored</u> text</p><p><br></p>
问题<p><br></p>
HTML连接到其他元素,因此它本身不是字符串或子字符串。
有一些正则表达式魔术可以帮助我吗?
答案 0 :(得分:0)
遍历<p>
标记,并根据标记是否恰好有一个子代且该子代是filter
来<br>
对其进行迭代。然后,.remove()
个通过测试的<p>
个>
[...postNode.querySelectorAll('p')]
.filter(p => p.children.length === 1 && p.children[0].tagName === 'BR')
.forEach(p => p.remove());
console.log(postNode.innerHTML);
<div id="postNode">
<h2>This is a heading two</h2>
<p>This is a paragraph</p>
<p><br></p>
<p>This is a paragraph with a <strong>bold</strong> an <em>italic</em> and an <u>underscored</u> text</p>
<p><br></p>
</div>
答案 1 :(得分:0)
我认为您可以使用类来隐藏要隐藏的元素
display: none;