I want to get a DOM element with jQuery but i want to only look backwards in the DOM.
So suppose i have the following HTML structure:
<div id="content">
<div id="first-module" class="module">
<h3>Some Module</h3>
<p>Lorem ipsum... </p>
<div id="some-other-content">
<div id="second-module" class="module">
<h3>Some other module</h3>
<p>Dolor sit amet...</p>
<button class="trigger">Trigger 1</button>
</div>
</div>
<button class="trigger">Trigger 2</button>
<div id="third-module" class="module">
<h3>Another module</h3>
</div>
<div>
</div>
$('.trigger').click(function() {
// Traverse DOM to find closest .module class
});
So when i click on the Trigger 1
button i want it to find the div
with ID second-module
.
When i click on Trigger 2
i want it to find the div
with ID first-module
and not second-module
, because it's nested deeper than the Trigger 2
button is.
Is there a jQuery function for this?
Try using .closest()
$('.trigger').click(function() {
$(this).closest('.module');
});
Yes, we do have .closest() for this:
$('.trigger').click(function() {
// Traverse DOM to find closest .module class
var id = $(this).closest('.module').attr('id');
alert(id);
});
DEMO HERE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With