通过向后遍历DOM获取最接近的元素

时间:2013-04-20 16:43:32

标签: javascript jquery

我想用jQuery获取DOM元素,但我只想在DOM中向后看。

假设我有以下HTML结构:

<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
});

因此,当我点击Trigger 1按钮时,我希望它能够找到ID为div的{​​{1}}。

当我点击second-module时,我希望它找到标识为Trigger 2 div的{​​{1}},因为它的嵌套深度超过first-module second-module按钮是。

是否有jQuery函数?

3 个答案:

答案 0 :(得分:4)

尝试使用.closest()

$('.trigger').click(function() {
    $(this).closest('.module');
});

答案 1 :(得分:4)

是的,我们确实有.closest()

$('.trigger').click(function() {
    // Traverse DOM to find closest .module class
    var id = $(this).closest('.module').attr('id');
    alert(id);
});

DEMO HERE

答案 2 :(得分:1)

另一种访问方法是使用parent selector

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