Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide multiple list items if one has no content or empty

I have a whole bunch of list items, and within them are more list items.

For all <li id="company-name" class="hide">, I want to detect whether this element is empty.

If it is empty, I want to hide ALL <li class="hide"> within the direct parent <ul></ul> element.

<ul>
    <li>
        <ul class="greyul">
            <li>Location:</li>
            <li class="hide">Company:</li> <!-- DONT HIDE -->
        </ul>
        <ul class="whiteul">
            <li>Melbourne</li>
            <li id="company-name" class="hide"></li> <!-- HIDE -->
            <li class="hide">Sydney</li> <!-- HIDE ALSO-->
        </ul>
    </li>
</ul>
like image 225
Kim Tran Avatar asked Sep 01 '15 04:09

Kim Tran


2 Answers

You can use simple css selector :empty

.hide:empty{
    display: none;
}

Using jQuery:

$('.hide:empty').hide();

If you want to hide parent div, then you may use:

$('.hide:empty').parent().hide();

As per your updated question, you can use not selector and contains selector like this:

$('.hide:not(:contains("Company:"))').hide();
like image 196
Bhojendra Rauniyar Avatar answered Oct 30 '22 23:10

Bhojendra Rauniyar


You have used multiple id="company-name" in your HTML, which is not a correct procedure. Change them to class.

You can use each() function to iterate.

$('li.company-name').each(function(){
    if( $.trim($(this).text()) == '')
        $(this).parents('li:first').find('.hide').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
  <li>
    <ul class="greyul">
      <li>Location:</li>
      <li class="hide">Company:</li>
    </ul>
    <ul class="whiteul">
      <li>Melbourne</li>
      <li class="company-name hide">display;none; on all items with the class 'hide' within THIS PARENT LIST item only, if this li has no content</li>
    </ul>
  </li>

  <li>
    <ul class="greyul">
      <li>Location:</li>
      <li class="hide">Company:</li>
    </ul>
    <ul class="whiteul">
      <li>Melbourne</li>
      <li class="company-name hide"></li>
    </ul>
  </li>

  <li>
    <ul class="greyul">
      <li>Location:</li>
      <li class="hide">Company:</li>
    </ul>
    <ul class="whiteul">
      <li>Melbourne</li>
      <li class="company-name hide">ABC</li>
    </ul>
  </li>

</ul>
like image 31
rrk Avatar answered Oct 30 '22 22:10

rrk