Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

dom - Shortest way to get last element by class name in javascript

I know that by using jQuery you can easily use :last selector to get the last element.

$(".some-element:last")

Although, this does not work with javascript.

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

What would be the best and shortest way to do the same thing in javascript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Take a look at the 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...