如何选择特定类的最后一个元素

rea*_*tor 5 javascript

我想知道为什么 foo 正在记录一个值,而 bar 却没有。它们在语法上似乎也相同。

编辑:这是一个 XY 问题。我的目标是获得该类的最后一个元素foo,我尝试使用last-child. 我尝试last-of-type过但没有成功。

const foo = document.querySelector(".some-element:last-child")
const bar = document.querySelector(".foo:last-child")

console.log('foo >>',foo)
console.log('bar >>',bar)
Run Code Online (Sandbox Code Playgroud)
<article>
  <div class="foo">This `div` is first.</div>
  <div class="foo">This <span>nested `span` is last</span>!</div>
  <div>This <em>nested `em` is first</em>, but this <em>nested `em` is last</em>!</div>
</article>
<ul>
  <li class="some-element">1</li>
  <li class="some-element">2</li>
  <li class="some-element">3</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

Ami*_*Bll 4

您可以用于querySelectorAll()按类选择所有元素。

为了获取带有类的最后一个元素,请尝试以下操作:

const bar = document.querySelectorAll(".foo")
console.log( 'bar >>', bar[bar.length - 1] )
Run Code Online (Sandbox Code Playgroud)

查看选择器概述