在javascript中按类名获取最后一个元素的最短方法 [英] Shortest way to get last element by class name in javascript
问题描述
我知道通过使用 jQuery
,您可以轻松使用:last
选择器来获取最后一个元素。
I know that by using jQuery
you can easily use :last
selector to get the last element.
$(".some-element:last")
虽然不可以使用javascript。
Although, this does not work with javascript.
document.querySelectorAll(".some-element:last")
什么是最好的在 javascript
中执行相同操作的最短路径?
What would be the best and shortest way to do the same thing in javascript
?
修改:
我没有带 id
属性的包装元素,这是我无法使用的方式 lastChild
。
I don't have a wrapper element with id
attribute, that's way I cannot use lastChild
.
推荐答案
看一下选择器概述
E:last-child
一个E元素,其父元素的最后一个孩子
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>
- 更新 -
如果您有其他元素不共享同一个类名,则可以尝试不同的方法,比如使用
If you have additional elements that do not share the same class name you can try a different approach like using
E:nth-last-of-type(n)
一个E元素,它的类型的第n个兄弟,从最后一个算起
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
的最后一个元素,只需执行
Or to only get the last element with class of .some-element
simply do
var someElementsItems = document.querySelectorAll(".some-element");
console.log(someElementsItems[someElementsItems.length -1])
这篇关于在javascript中按类名获取最后一个元素的最短方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!