简体   繁体   中英

How to hide a div when another div is empty

I'm new to jQuery and I've hit a bit of a snag.

Here is my HTML:

<div id="mainpage-tabs-area">
<ul class="nav cf">
    <li class="tb-one"><a href="#description" class="current">BTN1</a></li>
    <li class="tb-two"><a href="#tabtwo">BTN2</a></li>
    <li class="tb-three"><a href="#tabthree">BTN3</a></li>
    <li class="tb-four"><a href="#tabfour">BTN4</a></li>
</ul>

<div class="list-wrap">
    <ul id="description">
        <li>Hello, I am a description</li>
    </ul>

    <ul id="tabtwo" class="hide">
      <li></li>
    </ul>

    <ul id="tabthree" class="hide">
        <li></li>
    </ul>

    <ul id="tabfour" class="hide">
        <li></li>
    </ul>
</div> <!-- END List Wrap -->
            </div> <!-- END Organic Tabs -->

And here is my current jQuery:

$(document).ready(function () {
    var tabContent = $('ul.list-wrap').find('li').text();
    if ($.trim(tabContent) === "") {
        $('ul.nav li').hide();
    }
});

What I want to be able to do is just the jQuery to check every li in .list-wrap and if that li is empty then remove the corresponding li in .nav as this is for a tab system where if no content is entered, they don't want it displaying.

Any suggestions for a newbie?

Nick

I'd iterate through the list items, check the length of each node's text, and hide the corresponding tab with:

 $('.list-wrap li').each(function(i){ if(!$(this).text().length) $('#mainpage-tabs-area li').eq(i).hide(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="mainpage-tabs-area"> <ul class="nav cf"> <li class="tb-one"><a href="#description" class="current">BTN1</a> </li> <li class="tb-two"><a href="#tabtwo">BTN2</a> </li> <li class="tb-three"><a href="#tabthree">BTN3</a> </li> <li class="tb-four"><a href="#tabfour">BTN4</a> </li> </ul> <div class="list-wrap"> <ul id="description"> <li>Hello, I am a description</li> </ul> <ul id="tabtwo" class="hide"> <li></li> </ul> <ul id="tabthree" class="hide"> <li></li> </ul> <ul id="tabfour" class="hide"> <li></li> </ul> </div> <!-- END List Wrap --> </div> <!-- END Organic Tabs --> 

The i in the each() function is the index of the element that the loop is on, and that allows you to target the corresponding tab element and hide it.

This should do the job:

$('.list-wrap ul li').each(function(){
    var cnt = $('.list-wrap ul li').index( $(this) );
    var txt = $(this).text();
    if ($.trim(txt)==''){
        $('.nav li').eq(cnt).hide();
    }
});

jsFiddle Demo

I would suggest this If you are not making infinite lists

 $('.tb-two').hide(); //if tabtwo is empty $('.tb-hree').hide(); //if tabthree is empty and so on... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM