How to get last element by class name in JavaScript

How to get last element using a class name using JavaScript

Posted by Ervin Adams on August 9, 2022

How to get last element by class name in JavaScript

How to get last element using a class name using JavaScript

Posted by Ervin Adams on August 9, 2022

Let's look at some ways you can get the last element using JavaScript.

Here is the example html:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 Get last element using class name</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
  <main>
    <!--Main layout-->
    <div class="container">
        <div class="col-9 pt-5 mx-auto">
            <div class="txt">Lemon</div>
            <div class="txt">Orange</div>
            <div class="txt">Lime</div>
            <div class="txt">Grape</div>
        </div>
    </div>
  </main>
</body>
</html>

JS

Option 1. Use querySelectorAll() and class selector with pseudo-class

let lst = document.querySelectorAll(".txt:last-child");
console.log(lst[0].innerText);//Grape

Option 2. Get the length of elements using class minus 1

let lst = document.querySelectorAll(".txt");
console.log(lst[lst.length -1].innerText);//Grape

Option 3. Use querySelectorAll() to create object, then convert NodeList object to array

let lst = document.querySelectorAll(".txt");
console.log(Array.from(lst).pop().innerText);//Grape

Option 4. Use getElementsByClassName() to create object, then convert NodeList object to array

let lst = document.getElementsByClassName("txt");
console.log(Array.from(lst).pop().innerText);//Grape