Search code examples
javascriptwordpresshideis-empty

Hide a li if div is empty?


I've looked around for about a week or so now trying various techniques but so far no luck.

I am using javascript based tabs to tab out content on a page. The content is dynamically generated from Wordpress custom fields. If the div has no content to display in the HTML I would like that corresponding tab to not appear. Is this possible?

my code is as such:

<ul class="tabs">
<li class="tab1"><a href="#view1">Tab 1</a></li>
<li class="tab2"><a href="#view2">Tab 2</a></li>
<li class="tab3"><a href="#view3">Tab 3</a></li>

<div class="tabcontents">

<div id="view1">

<div class="noScreen">
<h2>Tab 1</h2>
</div>

<div class="view1">
<?php the_field('tab1'); ?>
</div>

</div>
<!--end Tab1-->

<div id="view2">

<div class="noScreen">
<h2>Tab 2</h2>
</div>

<div class="view2">
<?php the_field('tab2'); ?>
</div>

</div>
<!--end Tab2-->

<div id="view3">

<div class="noScreen">
<h2>Tab 3</h2>
</div>

<div class="view3">
<?php the_field('tab3'); ?>
</div>

</div>
<!--end Tab1-->

</div>
<!--end tabcontents-->

So if Tab1 and Tab3 respond back with data from the post but Tab 2 is empty I would like to hide the li for Tab 2 up above.

Can anyone help?

thank you in advance


Solution

  • I had to fix some missing tags and quotes from your HTML above, but this seems to do the trick.

    JSFiddle:

    http://jsfiddle.net/Q27K6/

    $(function(){
        $('div.tabcontents > div').each(function(index){
            var innerView = $(this).find('div[class^="view"]');
            var innerHtml = $(innerView).html();
            if(innerHtml.trim() == ''){
                $(this).hide();
                $('ul.tabs').find('li').eq(index).hide();
            }
        });
    });