Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove elements with whitespace?

Tags:

jquery

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

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

But, when there is a space...

<h2> </h2> 

...this does not work.

I tried

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

Also no luck. Can someone help with this?

like image 811
Laurence L Avatar asked Oct 28 '11 01:10

Laurence L


People also ask

How do I get rid of white space in HTML?

Line Height Property: The CSS line-height-property can be used to set the height of the line, whose value is set to normal, by default. By setting the height of the container at 0%, the white space can be removed.

How do I remove white spaces in Python?

strip(): The strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.


2 Answers

You can match elements with only whitespace 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 a HTMLCollection, NodeList (or otherwise not an Array), use Array.filter(elements, fn) or turn elements into an Array with Array.prototype.slice.call(elements).

If you didn't have to support older browsers too, you could use return ! (element.textContent || element.innerText).trim().

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

jsFiddle.


Alternatively, with working with nodes only...

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.

like image 158
alex Avatar answered Oct 19 '22 23:10

alex


try this

$("h2").each(function(){
   var self = $(this);
   if ( self.html().trim().length == 0 )
   {
     self.remove();
   }
});
like image 21
gurvinder372 Avatar answered Oct 20 '22 01:10

gurvinder372