Search code examples
jquerywhitespaceis-empty

jQuery if div empty


I'm working on wordpress template where div.post-thumb is empty but have dynamic white spaces.

<div class="post-thumb">    </div>
<div class="post-text"></div>

I'm using following script to detect if div.post-thumb is empty.

$('.post-thumb').each(function(){
if ($(this).html()=='') $('.post-text').css('marginLeft','50px');
}); 

Problem with this script is "Dynamic white spaces within div.post-thumb"

How to get rid of this issue? Is there any other way to detect if div is empty excluding white spaces?


Solution

  • You can use the jQuery trim function to remove whitespace:

    $('.post-thumb').each(function(){
        if($.trim($(this).html()) == '') $('.post-text').css('marginLeft','50px');
    }); 
    

    trim removes all spaces, new lines and tabs from the beginning or end of a string. See the jQuery docs for more information.