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 badges3 Answers
Reset to default 4Try 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
版权声明:本文标题:javascript - Get closest element by traversing DOM backwards - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741938505a2406000.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论