我正在尝试从DOM树中删除所有空标记。空意味着完全为空(如<a></a>
)和几个空格(如<a> ...</a>
)。还应删除内部空标签。 E.g。
<p style="text-align:right;"> <a> </a> <a></a></p><p>Hello</p>
应该离开
<p>Hello</p>
因为在删除空<a> </a> <a></a>
后,空<p style="text-align:right;"> </p>
仍会保留,应该删除。
我在做什么:
$.(".container>*:empty").remove();
结果令人困惑。我已经开始使用这样的代码进行调试:
console.log($.(".container>*:empty").size());
1)字符串:
Well, though it looks like a paragraph, it's not o_O.
0 (I'm wrapping string in global wrapper .container)
2)字符串
<a></a><a>Well, though it looks like a paragraph, it's not o_O.</a>
1
3)字符串
<a> </a><a>Well, though it looks like a paragraph, it's not o_O.</a>
0 (It seems one whitespace makes a non-empty)
4)字符串
<p> <a></a></p> <a>Well, though it looks like a paragraph, it's not o_O.</a>
0 (<a></a> is not selected as empty (maybe 'cause it's inside of < p>).
Also p is not selected, besides it contains only empty < a>)
我的问题是:
:empty
同时选择空标签和1-N空格?:empty
选择每个对象中的所有空标记?我的想法是${"*:empty"}.remove() while $('*:empty').size() > 0
。
更新
do {
$(".container *").filter(function() {
return $.trim(this.innerHTML) === ""
}).remove();
} while ($(".container *").filter(function() {
return $.trim(this.innerHTML) === ""
}).size() > 0)
console.log($(".container").html())
将此代码应用于:
<p> <p> <a> <a> <a><br><hr></a> </p> <a>Well, though it looks like a paragraph, it's not o_O.</a></p>
我们得到:
<p> <a>Well, though it looks like a paragraph, it's not o_O.</a></p>