Reputation: 279
I have several <div>
elements of different classes within each <li>
element. If one of them having a testsimonial-content
class is empty, how can I hide another div
of class testsimonial-heading
within the same <li>
as well? It shouldn't affect other <li>
s.
Here is my HTML code:
<ul>
<li>
<div class="testsimonial-heading">Testimonial</div>
<div class="testsimonial-content">Hello this is a testimonial</div>
</li>
<li>
<div class="testsimonial-heading">Testimonial</div> <!--This div should be hidden-->
<div class="testsimonial-content"></div>
</li>
<li>
<div class="testsimonial-heading">Testimonial</div>
<div class="testsimonial-content">Hello this is a testimonial</div>
</li>
</ul>
Upvotes: 0
Views: 866
Reputation: 34244
It is as simple as this:
$(document).ready(function() {
$(".testsimonial-content:empty").parent().hide();
// if content is empty - then hide
});
or this one if you need to hide li
if any of div
s is empty
$(document).ready(function() {
$(".testsimonial-content:empty, .testsimonial-heading:empty").parent().hide();
// if content OR heading is empty - then hide
});
Here is the working JSFiddle demo.
Update from the OP:
Sorry I actually have more than 2 divs within each li, can you make it hide the class .testimonial-heading? What would be the updated javascript for this? Instead of hiding parent.
Here you go:
$(document).ready(function() {
$(".testsimonial-content:empty").siblings(".testsimonial-heading").hide();
// if content is empty - then hide heading in this li only
});
Updated JSFiddle.
Upvotes: 1
Reputation: 15565
$('#ul li').each(function() {
var div = $(this).find('.testsimonial-content');
console.log(div.text().length);
if (div.text().length === 0) {
div.siblings('.testsimonial-heading').hide();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id='ul'>
<li>
<div class="testsimonial-heading">Testimonial</div>
<div class="testsimonial-content">Hello this is a testimonial</div>
</li>
<li>
<div class="testsimonial-heading">Testimonial1232131</div>
<!--This div should be hidden-->
<div class="testsimonial-content"></div>
<div class="testsimonial-">Other div</div>
</li>
<li>
<div class="testsimonial-heading">Testimonial</div>
<div class="testsimonial-content">Hello this is a testimonial</div>
</li>
</ul>
Find the class testsimonial-content
using .find()
get its length using .length
and if zero hide its sibling using .siblings().hide()
Upvotes: 1