Remove elements with only a space using jQuery
Is there a way to r开发者_开发知识库emove this
<p> </p>
using jQuery?
Try:
$('p')
.filter(function() {
return $.trim($(this).text()) === '' && $(this).children().length == 0
})
.remove()
What that does is it finds all the <p>
s that have nothing in them, and removes them from the DOM.
As Greg mentions above, testing the trimmed .text() will remove paragraphs w/ no text, but do have a self-contained element like the <img>
tag. To avoid, trim the .html() return. As text is considered a child element in the DOM, you'll be set.
$("p").filter( function() {
return $.trim($(this).html()) == '';
}).remove()
This could be a better solution for CMSs. Some rich text editors add
inside empty paragraphs.
$("p").filter( function() {
var html = $(this).html();
if(html == '' || html == ' ')
return true;
}).addClass('emptyP');
Probably same answer as here, try to do this on code behind.
With jquery i'll use this:
$("p:empty").remove();
Also you could use .empty(), that will remove all child nodes from the set of matched elements.
$("p").filter( function() {
return $.trim($(this).html()) == '';
}).remove()
I used this to remove empty paragraph that contains not element such as IMG, Input, Select, etc.
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/
This should handle any element with no children of any type (including unwrapped text nodes).
$("p").filter(function() {
return !this.childNodes[0]
}).remove();
give it an id (to get the selector).
<p id="myP"></p>
<script>
$("#myP").remove();
</script>
精彩评论