2

Let's supose i have this HTML:

<ul class="nested">
    <li>text</li>
    <li>text</li>
    <li>text</li>
</ul>

<ul class="nested">
</ul>

<ul class="nested">
    <li>text</li>
    <li>text</li>
    <li>text</li>
</ul>

I would like to check which ul has no li, when page get loaded, and hide it.

It can be done using jquery as well.

Thanks,

3 Answers3

6

You only need CSS

The :empty pseudo selector will select elements that contain either nothing or only an HTML comment.

div:empty {
   display: none;
}

Source https://css-tricks.com/almanac/selectors/e/empty/

1

You can do this using the following jQuery.

 window.onload = function(){ // When the page has finished loading.
    $(".nested").each(function(){ // Check every "nested" class 
    if($(this).children().length == 0){ // If this nested class has no children
        $(this).hide(); // This will hide it, but not alter the layout
        // $(this).css("display", "none"); // This will alter the layout
        } else{
        $(this).show();
        //$(this).css("display", "none"); // This will alter the layout
        }
     }
}

Or, as user Rory McCrossan suggested, much more simply written :

window.onload = function(){
    $('.nested:not(:has(li))').hide(); // Will not alter layout
    // $('.nested:not(:has(li))').css("display", "none"); // Will alter layout
    }
cmprogram
  • 1,854
  • 2
  • 13
  • 25
0

To do that by jQuery you can use $.each in jQuery...also theres a lot of possible option can resolve this issue

$(".nested").each(function(index){
    if(!$(this).find("li").length){
        $(this).hide();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nested">
    <li>text</li>
    <li>text</li>
    <li>text</li>
</ul>

<ul class="nested">
</ul>

<ul class="nested">
    <li>text</li>
    <li>text</li>
    <li>text</li>
</ul>
Anees Hikmat Abu Hmiad
  • 3,460
  • 2
  • 19
  • 36