Using JQuery to “Hide” Empty Divs

So, I thought it was about time for me to start blogging again.  So much for weekly.  I will shoot for monthly this time!

Anyway, here’s today scenario:

I have a page layout with several fields (plain text or rich html) exposed.  The template is meant to be used for corporate policies which can be very long with many sections or very short with one section and anywhere in between.  What I needed to do was remove the   from child divs that only contained that in the html.

Solution:
With the use of some jquery and a bit of trial and error the code below will do exactly what I wanted.  When the page is rendered the empty lines are removed.  When the page is edited all the field controls are still shown accordingly.

$(document).ready(function() {
$(’.<divclassgoeshere>’).each(function() {
var value=$(this).children(”:first”).html().toLowerCase();
if(value==’&nbsp; ‘) {
$(this).remove();
}
});
});

Enjoy!

Tags: , ,

4 Responses to “Using JQuery to “Hide” Empty Divs”

  1. David Fast Says:

    Hello,
    I’m also trying to hide the empty divs on my Sharepoint 2007 site. However, I’m not very familiar with JQuery or Javascript.
    I’ve copied your script and saved it in a file called remove_spaces.js. I’m also calling in a JQuery library. I’m calling both of these files in within the head of my master page like this:

    Is this the correct way to apply JQuery? I think I’m missing a step or two.
    Thanks,
    David

  2. David Fast Says:

    Sorry, my copied code didn’t paste in properly. I’m calling in the JS files in the head like this:

  3. David Fast Says:

    I guess the carrots are causing my copy and pasting problems. Once again, the code I’m using is:

    script type=”text/javascript” src=”Style Library/en-us/CustomStyles/JS/jquery-1.4.2.min.js”/script

    script type=”text/javascript” src=”Style Library/en-us/CustomStyles/JS/remove_space.js”/script

  4. gregc Says:

    Hi David - That is the correct way to implement jQuery. Generally I prefer to have my source files in the _layouts directory, but I think the way you’ve implemented it would work. A couple things to try:

    1) In your script tags in your masterpage, add a leading / to the src attribute;
    2) Make sure you’ve replaced in my sample above with the appropriate div that you’d like to remove the  s from. this includes removing the tags.

    Greg

Leave a Reply