Search code examples
javascriptjqueryjquery-selectorsparent-childsiblings

Target next siblings child to get outerheight


I'd like to get the height value of the class .child in the example below and then use an alert to display the value for troubleshooting.

I have two elements .first and .second that are siblings, the .second element has a child called .child

The HTML:

<div class="parent">

  <div class="first">Click Me</div>

  <div class="second">
    <div class="child"></div>
  </div>

</div>

The CSS:

.first {
   width: 60px;
   padding: 8px;
   background: blue;
}

.child {
   height: 1234px;
}

The jQuery:

$(".first").click(function() {

  var childHeight = $(this).next(".second > .child").outerHeight();

  alert(childHeight);

});

The problem seems to be in targeting the child, if I remove the > .child from my var it returns the height of .second

Here is a JS fiddle with the same code: https://jsfiddle.net/CultureInspired/6dxLp86b/


Solution

  • You should use .next(".second").find(".child") to get the child element correctly.

    This will get the next element and then will find the .child element inside that.

    $(".first").click(function() {
    
      var childHeight = $(this).next(".second").find(".child").outerHeight();
      alert(childHeight);
    
    });
    .first {
      width: 60px;
      padding: 8px;
      background: blue;
    }
    
    .child {
      height: 1234px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="parent">
    
      <div class="first">Click Me</div>
    
      <div class="second">
        <div class="child"></div>
      </div>
    
    </div>