我想从我的页面中删除空<p></p>
。这适用于$('p:empty').remove();
。但是我的页面上也有一些<p>
,看起来像这样(只包含很多空格):
<p>
</p>
不幸的是,他们不被认为是空的。
如何删除它们?
答案 0 :(得分:5)
这样的事情应该有效:
$('p').each(function() {
if ($(this).text().trim().length == 0) {
$(this).remove()
}
});
答案 1 :(得分:2)
使用此方法:
1-获取它的内部html 2-修剪它 3 - 将它与&#34;&#34;
进行比较$('p').each(function() {
var $p = $(this);
if($.trim($p.html())==='') {
$p.remove();
}
});
答案 2 :(得分:1)
You can use RegEx for this. We simply look for anything that starts and ends with spacing with nothing in between(line breaks, spaces, tabs): ^\s+$
and remove the node. We do the same if the node contains nothing^$
.
let paragraphs = document.querySelectorAll("p");
paragraphs.forEach(paragraph => {
if ((/^\s+$|^$/gm).test(paragraph.textContent)) paragraph.parentNode.removeChild(paragraph);
});
let paragraphs = document.querySelectorAll("p");
paragraphs.forEach(paragraph => {
if ((/^\s+$|^$/gm).test(paragraph.textContent)) {
paragraph.parentNode.removeChild(paragraph);
console.log(paragraph, "removed");
}
});
<p>
</p>
<p> hola </p>
<p> </p>
<p> </p>
<p> hiya </p>
<p> </p>
<p></p>