2 回答
TA贡献1796条经验 获得超4个赞
您可以尝试使用.parents()
OR .closest()
:
console.log($('.need-ID-of-class-2').closest('.2').attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="1">
<div class="2" id="1">
<div class="3">
<div class="4">
<input class="need-ID-of-class-2" value="">
</div>
</div>
</div>
</div>
TA贡献1789条经验 获得超10个赞
访问最近祖先元素的不同方法是,closest(),parents(),querySelector和closest()。
$('.need-ID-of-class-B').closest('.B').attr('id');
$('.need-ID-of-class-B').parents('.B').attr('id');
document.querySelector('.need-ID-of-class-B').closest("div .B").getAttribute('id');
TA贡献1887条经验 获得超5个赞
使用.closest([class="2"])您可以获得匹配的祖先.2,并获取其ID:
const input = document.querySelector('input');
console.log(input.closest('[class="2"]').id);
<div class="1">
<div class="2" id="1">
<div class="3">
<div class="4">
<input class="need-ID-of-class-2" value="">
</div>
</div>
</div>
</div>
如果可能的话,修复您的 HTML,使其类有效 - 类名不应以数字开头。然后你可以使用.而不是[class]:
const input = document.querySelector('input');
console.log(input.closest('.two').id);
<div class="1">
<div class="two" id="1">
<div class="3">
<div class="4">
<input class="need-ID-of-class-2" value="">
</div>
</div>
</div>
</div>
- 2 回答
- 0 关注
- 91 浏览
添加回答
举报