user3108268
user3108268

Reputation: 1083

Hide element only if child exists

Multiple parent with different amount of child elements, eg:

<div class="items">
  <div></div>
  <div>hide this child</div>
  <div></div>
</div>

<div class="items">
  <div></div>
  <div>don't hide this child</div>
</div>

Can be almost solved with this:

if ($(".items div:nth-child(3)").length) {
    $(".items div:nth-child(2)").hide();
}

It hides the second div in both parents, but it should hide only in first parent, because second parent doesn't have a third child.

Upvotes: 0

Views: 266

Answers (2)

User863
User863

Reputation: 20039

Using CSS last-child

.items div:nth-child(2):not(:last-child) {
  display: none;
}
<div class="items">
  <div></div>
  <div>hide this child</div>
  <div></div>
</div>

<div class="items">
  <div></div>
  <div>don't hide this child</div>
</div>

Using Jquery

$(".items div") selects all child div. So you can use each() to select child from different parent

$(".items").each(function() {
  if ($("div", this).length > 2) {
    $("div:nth-child(2)", this).hide();
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="items">
  <div></div>
  <div>hide this child</div>
  <div></div>
</div>

<div class="items">
  <div></div>
  <div>don't hide this child</div>
</div>

Note: descendant selector (space) selects all both children and grandchildren. If you need only children use child selector (>)

Upvotes: 3

blurfus
blurfus

Reputation: 14031

Your selector is grabbing all .items in the document so it's pretty much always going to hide the second one.

Instead, you want to evaluate the children of each item separately to determine if it should be hidden or not.

See demo code below

$(function() {
  // get all the items
  var items = $(".items");

  // check their children, if more than 2 children, hide them
  $.each(items, function(idx, item) {
    if ($(item).children().length > 2) {
      $(item).hide();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="items">
  <div></div>
  <div>hide this child</div>
  <div></div>
</div>

<div class="items">
  <div></div>
  <div>don't hide this child</div>
</div>

Upvotes: 1

Related Questions