开发者

Removing all empty p-Tags

开发者 https://www.devze.com 2023-03-26 06:41 出处:网络
i need your help with an regex in Javascript, again. Sometimes i have empty p-Tags in the DOM and i will remove them all.

i need your help with an regex in Javascript, again.

Sometimes i have empty p-Tags in the DOM and i will remove them all.

Some look like:

<p></p>

others like:

<p> </p>

I think for a开发者_运维技巧n regex pro is this very lame, but i'm not good with it :(

so thanks in advance :)


You don't need to use regex for something this simple. Most likely you need to iterate over all the 'p' elements anyway. Something like this works:

http://jsfiddle.net/mqchen/3pV2P/

$('p').each(function(index, item) {
    if($.trim($(item).text()) === "") {
        $(item).slideUp(); // $(item).remove();
    }
});


A very basic regex for this:

<p>\s*<\/p>

And here's a simple RegEx Tester for Firefox that might help you in the future. I use it quite a bit.


that's some methods that helps sometimes

$('p:empty').hide()
p:empty { display: none; } 


The accepted answer is of course completely correct but since the poster asked for how to use regular expressions, here is a regex version (for completeness if you will) that does just that:

$('p').map(function() {
   if( /^[\s ]*$/.test($(this).text()) ) {
      $(this).remove();
   }    
});

Note a better regex version can be achieved by using the jQuery regex selector extension

0

精彩评论

暂无评论...
验证码 换一张
取 消