Reputation: 1692
In my code a button should allow the user to hide a nearby div. To make things abstract, whenever a button has a data-collapse="true" attribute, jQuery should look for the closest element of class "collapsable" and hide it. The problem is, in my page, there will be different cases of hierarchy, so .closest() won't always work. Let me point out some of the possible cases:
First case:
<a data-collapse="true"></a>
<div class="collapsable"></div>
Second case:
<div class"controls">
<a ...></a>
<a ...></a>
<a data-collapse="true"></a>
</div>
<div class="collapsable"></div>
Third case:
<div class="collapsable">
...
<a data-collapse="true"></a>
</div>
There might be more cases potentially.
My question: Is there a universal method to call on the a-button to look for the nearest div of class "collapsable" regardless of which direction to look for? Like, just zooming out in both directions until a match is found?
Upvotes: 0
Views: 104
Reputation: 26360
Here's what I came up with : a recursive search in the clicked element's parents.
I have illustrated the code with heavily nested and separated couples examples, run it below.
$("a[data-collapse=true]").click(function() {
var $elem, $searchIn, max, result;
$searchIn = $(this);
$elem = null;
result = null;
max = 50; // Max recursiveness
while (($elem === null) && max) {
result = $searchIn.find('.collapsable');
if (result.length) {
$elem = result.first();
}
$searchIn = $searchIn.parent();
max--;
}
$elem.css("border", "red dashed 2px");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><a href="#" data-collapse="true">Click me</a>
<div class="collapsable">I should get red</div>
</div><br/><br/>
<div>
<div>
<a href="#" data-collapse="true">Click me</a>
</div>
<div>
<div class="collapsable">I should get red</div>
</div>
</div><br/><br/>
<div>
<div>
<div>
<a href="#" data-collapse="true">Click me</a>
<div>
<div>
<div>
<div class="collapsable">I should get red</div>
</div>
</div>
</div>
</div>
</div>
</div><br/><br/>
<div>
<div>
<div>
<div>
<div>
<div><a href="#" data-collapse="true">Click me</a></div>
</div>
</div>
</div>
<div>
<div>
<div>
<div>
<div>
<div class="collapsable">I should get red</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Upvotes: 1
Reputation: 74738
Your question:
Is there a universal method to call on the a-button to look for the nearest div of class "collapsable" regardless of which direction to look for?
in short i would answer it: No! there is not.
But you could check for the elements like this, may be this could help:
var $collapsable = $('a[data-collapse="true"]').next('.collapsable') ||
$('a[data-collapse="true"]').prev('.collapsable') ||
$('a[data-collapse="true"]').parent().next('.collapsable') ||
$('a[data-collapse="true"]').parent().prev('.collapsable') ||
$('a[data-collapse="true"]').parent().find('.collapsable') ||
$('a[data-collapse="true"]').closest('.collapsable');
Upvotes: 1