greatwanderer greatwanderer - 18 days ago 4
jQuery Question

How to target the specific parent class a child div is nested within?

I need to hide the parent div (i.e., .post) when the child div (i.e., post-title) is empty. However, I don't want to hide the other child div if it contains content.

This is what I have going on:

<div id="latest">
<div class="post">
<div class="post-content">
<div class="post-title"></div>
</div>
</div>
<div class="post">
<div class="post-content">
<div class="post-title"><h2>Hello!</h2></div>
</div>
</div>
</div>





$(".post-title:empty").parent($(".post")).hide();

Answer

Use closest() to get the closest parent with the class of post

$(".post-title:empty").closest('.post').hide();

 $(".post-title:empty").closest('.post').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="latest">
  <div class="post">
    <div class="post-content">
      <div class="post-title"></div>
      <p>content</p>
    </div>
  </div>
  <div class="post">
    <div class="post-content">
      <div class="post-title">
        <h2>Hello!</h2>
      </div>
       <p>content hello</p>
    </div>
  </div>
</div>