简体   繁体   中英

Hide Div When Content == “0” Using JQuery?

Trying to write a script that checks the content of a div, and if that content is exactly 0 than it hides the div. This is for an inbox system so that the count only shows if you have a new message. This is what I wrote:

 var count = $('.count').val(); if (count == '0') { $('.count').hide(); } else { $('.count').show(); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href='index.php?act=UserCP&CODE=alerts'> <span class="count"><.-- |new_alerts| --></span> alerts</a> <a href='index?php?act=Msg&CODE=01'> <span class="count"><!-- |new_msg| --></span> inbox</a>

Site Where the Problem is Occurring.

The <!--|new_msg| --> <!--|new_msg| --> is part of the hosting site's user menu system. On the site it changes to a number, correlating to how many new alerts or new messages you have. Is this the reason? The div has an actual number on the site, so it should read that right?

I haven't figured out why but I have zero luck getting class selectors to work. Try setting an id on the element. And then...

var count = $(document).getElementById("#countId").textContent;
if (count == '0') { 
    $(document).getElementById("#countId").style.display = 'none'; 
} 
else { 
    $(document).getElementById("#countId").style.display = ''; 
}

If you've multiple .count elements this is exactly what count variable will return [See The Next Code] .. And for sure it will not match 0 at all

 $(document).ready(function(){ var count = $(".count").text().trim(); console.log(count); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="count">0</span> <span class="count">1</span> <span class="count">2</span>

The right way is to loop through the .count elements using .each or even .filter

 $(document).ready(function(){ $(".count").show(0).filter(function(){ return $(this).text().trim() == 0; }).hide(0); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="count">0</span> <span class="count">1</span> <span class="count">2</span>

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