Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get closest element by traversing DOM backwards

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?

like image 543
Vivendi Avatar asked Jan 13 '23 14:01

Vivendi


2 Answers

Try using .closest()

$('.trigger').click(function() {
    $(this).closest('.module');
});
like image 126
Mohammad Adil Avatar answered Jan 19 '23 10:01

Mohammad Adil


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

like image 31
palaѕн Avatar answered Jan 19 '23 12:01

palaѕн