Håkan Bylund
Håkan Bylund

Reputation: 64

Hide div when another div is empty

I know theres lots of answers on this problem, but I've read through all I can find but still cant get it to work.

I have a div which i need to be hidden if another div is empty, or just containing whitespace.

<div id="rt-main" class="mb12">
    <div class="rt-grid-12">
        <div class="rt-block component-block main-overlay-light">
            <div id="rt-mainbody">
                <div class="component-content">
                    <div class="blog-featured"></div>

( I want to hide div.mb12 when div blog-featured = ' ' )

My closest bet is this:

$(document).ready(function() {
   str = $('div.section').text();
   if($.trim(str) === "") {
     $('div.section').hide();
   }
});

But I get all sorts of errors in the console when trying.

Now I've got "TypeError: Cannot call method 'text' of null"

Upvotes: 0

Views: 1266

Answers (3)

James Montagne
James Montagne

Reputation: 78650

On the actual site (not included in the question), you have this:

jQuery.noConflict();

This makes it so that $ is no longer jquery. Most likely because one of the many other libraries you have included uses the $ name. You can simply change your code to use jQuery in place of $:

jQuery(document).ready(function() { ...

Alternatively, you can assign jQuery to a different variable name:

var $j = jQuery.noConflict();

$j(document).ready(function(){ ...

Upvotes: 1

cssyphus
cssyphus

Reputation: 40058

Are you loading the jQuery library before your script? Do you have something like this in the <head> tags of your page?

    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    </head>

    <script type="text/javascript">
        $(document).ready(function() {
        etc etc
    </script>

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

You want this -

jQuery(document).ready(function () {
    var str = jQuery('div.blog-featured').text();
    if (jQuery.trim(str) === "") {
        jQuery('div.mb12').hide();
    }
});

Demo ---> http://jsfiddle.net/PqXWJ/20/

Upvotes: 0

Related Questions