jQuery如何“空:” - 选择器有效吗? (删除空标签)

时间:2013-04-16 17:48:34

标签: jquery regex jquery-selectors is-empty

我正在尝试从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>

1 个答案:

答案 0 :(得分:4)

您应该查看filter()trim()

DEMO

$(".container *")
    .filter(function(){
         return $(this).is(':not(br)') 
                && $(this).is(':not(img)') 
                && $.trim(this.innerHTML) === ""
     }).remove();