Reputation: 20100
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
Reputation: 22845
This is the proper selector for your use case:
var header = clickable.closest("*:has(.header)").find(".header");
Upvotes: 2
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
Reputation: 20757
This would work:
var header = clickable.closest('.body').prev('.header');
Upvotes: 0
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