Shortest way to get last element by class name in javascript

To find the last child of an element you can use this:

var childrenCount = document.getElementById("myDIV").childNodes.length;
document.getElementById("myDIV").childNodes[childrenCount-1];

Follow these Steps:

  1. Find All Element: var elems = document.querySelectorAll(".some-element");
  2. Find Length: var len = elems.length;
  3. Get Last Element: var lastelement = len < 1 ? "" : elems[len-1];

querySelectorAll returns NodeList object which can be converted to Array. Then pop returns the last element.

ES2015 / ES6:

Array.from(document.querySelectorAll('.some-element')).pop();

Demo:

function addItem(withClass){
  document.body.insertAdjacentHTML('beforeend', withClass
    ? '<div class="some-element">with class</div>'
    : '<div>without class</div>'
  )
  
  findLastOfClass('.some-element')
}

function findLastOfClass(selector){
  var lastOfClass = [...document.querySelectorAll(selector)].pop()
  
  // temporarily highlight last-of-class
  if( lastOfClass ){
    lastOfClass.classList.add('highlight')
    setTimeout(()=> lastOfClass.classList.remove('highlight'), 1000)
  }
}
.highlight{ background: lightyellow }
<button onClick="addItem(true)">add item with class</button>
<button onClick="addItem()">add item without class</button>

Older browsers (IE8+):

Array.prototype.pop.call(document.querySelectorAll('.some-element'));

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>

--Update--

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)

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>

Or to only get the last element with class of .some-elementsimply do

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

Tags:

Javascript

Dom