ab11
ab11

Reputation: 20100

Find closest selector using JQuery?

For the below HTML and JQuery, the first two closest() calls find the expected element, but the third one does not find the header element. Is there a way to find it using jquery?

<div class="top">
  <div class="header"></div>
  <div class="body>
    <a href="#" class="js-clickable">clickable</a>
  </div>
</div>

$('.js-clickable').on('click', function (data) {

  var clickable = $(data.toElement);

  var top= clickable.closest('.top');
  var body= clickable.closest('.body');
  var header = clickable.closest('.header');

});

Upvotes: 0

Views: 194

Answers (4)

Robo Robok
Robo Robok

Reputation: 22845

This is the proper selector for your use case:

var header = clickable.closest("*:has(.header)").find(".header");

Upvotes: 2

Jay Blanchard
Jay Blanchard

Reputation: 34426

Because header is not an ancestor you can go a couple of ways.

var header = clickable.closest('.body').prev('.header');

You could also go to the clickable's grandparent and come back down.

Upvotes: 1

MonkeyZeus
MonkeyZeus

Reputation: 20757

This would work:

var header = clickable.closest('.body').prev('.header');

Upvotes: 0

lmgonzalves
lmgonzalves

Reputation: 6588

Change:

var header = button.closest('.header');

To:

var header = button.closest('.top').find('.header');

Learn more here: https://api.jquery.com/closest/

Upvotes: 0

Related Questions