如何定位具有tabindex属性的给定父级的最后一个元素?
例如:
<div id="popup">
<div id="some-element" tabindex="0">
<div id="some-other-element" tabindex="0">
<div id="yet-another-element" tabindex="0">
</div>
在这种情况下,它将定位到#yet-another-element
答案 0 :(得分:2)
您可以将属性选择器[...]
与jQuery .last()
结合使用:
let target = $('#popup [tabindex]').last();
console.log(target.attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup">
<div id="some-element" tabindex="0">
<div id="some-other-element" tabindex="0">
<div id="yet-another-element" tabindex="0">
</div>
另一种方法是使用jQuery :last
选择器:
$('#popup [tabindex]:last');
let target = $('#popup [tabindex]:last');
console.log(target.attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup">
<div id="some-element" tabindex="0">
<div id="some-other-element" tabindex="0">
<div id="yet-another-element" tabindex="0">
</div>
如果您需要选择特定的tabindex
值:
$('#popup [tabindex="0"]:last');
答案 1 :(得分:1)
使用JavaScript:
将Document.querySelectorAll()
与Attribute selectors
一起使用,以数组状对象的形式首先获取所有元素。然后使用Spread syntax
(...
)和array.length - 1
从最后一个索引中获取元素:
var div = document.querySelectorAll('#popup > div[tabindex="0"]');
var lastEl = [...div][div.length - 1];
console.log(lastEl.id)
<div id="popup">
<div id="some-element" tabindex="0"></div>
<div id="some-other-element" tabindex="0"></div>
<div id="yet-another-element" tabindex="0"></div>
</div>
使用jQuery:您可以将:last
用作选择器的一部分:
var lastEl = $('#popup > div[tabindex="0"]:last');
console.log($(lastEl).prop('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup">
<div id="some-element" tabindex="0"></div>
<div id="some-other-element" tabindex="0"></div>
<div id="yet-another-element" tabindex="0"></div>
</div>