Chris Cummings Chris Cummings - 1 day ago 4
jQuery Question

How do I target non-immediate parent of class

I have the following code:

$(".less").click(function(){
$(".myblurb").css('height', '220');
});


In a setup like this.

<div class="myblurb">
<p>Some text</p>
<p>A <a href="#" class="less">link</a></p>
</div>


I have 3 or more different "myblurb" DIVs on a page and sometimes the "less" link may be nested further down inside the "myblurb" DIV.

How do I target this specific "myblurb" only? It may or may not be an immediate parent of the "less" link.

Answer

Use closest() method to get the first ancestor in DOM tree.

$(".less").click(function() {
  $(this).closest(".myblurb").css('height', '220');
});

$(".less").click(function() {
  $(this).closest(".myblurb").css('height', '220');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myblurb">
  <p>Some text</p>
  <p>A <a href="#" class="less">link</a>
  </p>
</div>

Comments