Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide a div if content is empty

Philosophy bubble is like a quote/speech bubble div styled which has a sharepoint control inside, the richHtmlField which lets users to type in content while editing page, but if the user chooses to leave it empty, there will be no content in the div so only the bubble will show up in the page which will look funny so i wanna hide the whole div when there is no user entry or basically the div is empty?? How do you do this in jquery?

<div class="philosophy-bubble">
<PublishingWebControls:RichHtmlField FieldName="carephilosophy" runat="server"></PublishingWebControls:RichHtmlField>
</div>  
like image 935
AJSwift Avatar asked Nov 29 '11 16:11

AJSwift


People also ask

Can a div be hidden?

The hidden attribute hides the <div> element. You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <div> element is not visible, but it maintains its position on the page.

How do you hide a div if it is empty in jQuery?

$("#bar"). find('div. section:empty'). hide();

How do you toggle visibility of a div?

To toggle a div visibility in jQuery, use the toggle() method. It checks the div element for visibility i.e. the show() method if div is hidden. And hide() id the div element is visible. This eventually creates a toggle effect.


1 Answers

Use jQuery's :empty selector:

$('.philosophy-bubble:empty').hide();

Here's a working fiddle.

Alternative

You could also use the filter() function to find all empty div's and hide:

//All divs
$('div').filter(function() {
        return $.trim($(this).text()) === ''
}).hide()

//div's with a certain class
$('.philosophy-bubble').filter(function() {
        return $.trim($(this).text()) === ''
}).hide()

//div with a specific ID
$('#YourDivID').filter(function() {
        return $.trim($(this).text()) === ''
}).hide()

..etc.

Note: the :empty selector will be more performant. See jsPerf.

like image 81
James Hill Avatar answered Sep 25 '22 06:09

James Hill