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>
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();
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With