admin管理员组

文章数量:1313812

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?

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?

Share Improve this question asked Apr 20, 2013 at 16:43 VivendiVivendi 21.1k28 gold badges134 silver badges204 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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

Another way to access it is using parent selector

$('.trigger').click(function() {
   console.log($(this).parent('.module').attr('id'));
    // Traverse DOM to find closest .module class
});

本文标签: javascriptGet closest element by traversing DOM backwardsStack Overflow