微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在JavaScript中按类名获取最后一个元素的最短方法

我知道通过使用jQuery,您可以轻松地使用:last选择器来获取最后一个元素.

$(".some-element:last")

虽然,这不适用于javascript.

document.querySelectorAll(".some-element:last")

在javascript中做同一件事的最好和最短的方法是什么?

编辑:

我没有具有id属性的wrapper元素,因此无法使用lastChild.

解决方法:

看看Selectors Overview

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>

–Update–

如果您有其他元素使用不同的类名,则可以尝试使用不同的方法,例如使用

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-elements类的最后一个元素

var someElementsItems = document.querySelectorAll(".some-element");
console.log(someElementsItems[someElementsItems.length -1])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐