我正在尝试使用 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 连接到其他元素,因此它本身不是字符串或子字符串。
是否有一些正则表达式魔法可以帮助我?
遍历<p>
标签,并filter
根据标签是否只有一个孩子,并且该孩子是<br>
. 然后,通过该测试的.remove()
每个<p>
s:
[...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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句