How to remove items with spaces?

I can easily remove a tag that has no spaces ...

$('h2:empty').remove(); 

But when there is a space ...

 <h2> </h2> 

... this does not work.

I tried

 if ($('h2').html() == " "){ $('h2').remove(); } 

Also out of luck. Can anyone help with this?

+7
source share
5 answers

try it

 $("h2").each(function(){ var self = $(this); if ( self.html().trim().length == 0 ) { self.remove(); } }); 
-one
source

You can only match elements with white text with ...

 $('h2').filter(function() { return ! $.trim($(this).text()); }); 

To remove these elements, call remove() on the returned set.

jsFiddle .


Alternatively without jQuery ...

 elements.filter(function(element) { return ! (element.textContent || element.innerText).replace(/\s+/g, ''); }); 

If your elements is an HTMLCollection , NodeList (or otherwise not Array ), use Array.filter(elements, fn) or turn elements into Array with Array.prototype.slice.call(elements) .

If you did not need to support older browsers, you can use return ! (element.textContent || element.innerText).trim() return ! (element.textContent || element.innerText).trim() .

To remove them, loop over the elements and use thisElement.parentNode.removeChild(thisElement) .

jsFiddle .


Alternatively, when working only with nodes ...

 var containsWhitespace = function me(node) { var childNodes = node.childNodes; if (childNodes.length == 0) { return true; } for (var i = 0, length = childNodes.length; i < length; i++) { if (childNodes[i].nodeType == 1) { return me(childNodes[i]); } else if (childNodes[i].nodeType == 3) { return ! childNodes[i].data.replace(/\s+/g, ''); } } } elements.filter(containsWhitespace); 

jsFiddle .

+15
source

I do not use jQuery, but I can give a direct JavaScript solution:

 var elms = document.getElementsByTagName('h2'), l = elms.length, i; for( i=l-1; i>=0; i--) { if( elms[i].innerHTML.replace(/\s+/,"") == "") { elms[i].parentNode.removeChild(elms[i]); } } 

So just do what jQuery is equivalent to. I think so.

+1
source

To adapt to alex, try the following:

 $('h2').filter(function() { return $.trim($(this).text()).length == 0; }).remove(); 

see jsfiddle .

+1
source

This will only be checked for one place, but works for a basic example:

 $("h2:contains(' ')").remove() 
0
source

All Articles