我知道通过使用jQuery
,您可以轻松地使用:last
选择器来获取最后一个元素。
$(".some-element:last")
尽管如此,这不适用于 JavaScript。
document.querySelectorAll(".some-element:last")
在 javascript
中执行相同操作的最佳和最短方法是什么?
最佳答案
E:last-child
an E element, last child of its parent
console.log(document.querySelectorAll(".some-element:last-child"))
<ul>
<li class="some-element">1</li>
<li class="some-element">2</li>
<li class="some-element">3</li>
</ul>
--更新--
如果您有其他元素不共享相同的类名,您可以尝试不同的方法,例如使用
E:nth-last-of-type(n)
an E element, the n-th sibling of its type, counting from the last one
var lastLiItem = document.querySelectorAll("li:nth-last-of-type(1)");
var lastSomeElement = document.querySelectorAll("li:nth-last-of-type(2)");
console.log("This is the last li item in the list: ", lastLiItem[0]);
console.log("This is the last li item with class .some-element in the list: ", lastSomeElement[0]);
<ul>
<li class="some-element">1</li>
<li class="some-element">2</li>
<li class="some-element">3</li>
<li>4</li>
</ul>
或者只获取类为 .some-element
的最后一个元素,只需这样做
var someElementsItems = document.querySelectorAll(".some-element");
console.log(someElementsItems[someElementsItems.length -1])
关于javascript - 在javascript中通过类名获取最后一个元素的最短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39223343/