Remove elements with only a   space using jQuery

后端 未结 8 766
北恋
北恋 2020-11-30 07:34

Is there a way to remove this

using jQuery?

8条回答
  •  无人及你
    2020-11-30 08:24

    If you are trying to simply remove all empty P elements, or P's with only a single space, then you could do this:

    $('p').map( function(){
      var html = $(this).html();
      if( !html.length || html == ' ' || html == String.fromCharCode(255) )
        return this;
    }).remove();
    

    This iterates through all of the P's on your page and if they match a certain criteria (they are empty or only have a whitespace) then it removes them from the DOM.

    Also, by assigning our html content once to a local variable, it helps the script run faster. To look for non-breaking spaces I simply compare the contents to a string created from ASCII character code 255 (which is a non-breaking space).

    jQuery's map() function can be great when a simple filter, or attribute comparison will not suffice.

    You can read more about it here.... http://api.jquery.com/map/

提交回复
热议问题