How to get the first element by class name in JavaScript

How to get the first element by class name using JavaScript

Posted by Ervin Adams on August 10, 2022

How to get the first element by class name in JavaScript

How to get the first element by class name using JavaScript

Posted by Ervin Adams on August 10, 2022

Let's look at some ways you can get the first element by class name using JavaScript.

Here is the example html:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 Get first 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 frt = document.querySelectorAll(".txt:first-child");
console.log(frt[0].innerText);//Lemon

Option 2. Use querySelectorAll() method

let frt = document.querySelectorAll(".txt");
console.log(frt[0].innerText);//Lemon

Option 3. Use getElementsByClassName() to create object, then convert NodeList object to array using Array.from() method to get first position using the index.

let frt = document.getElementsByClassName("txt");
console.log(Array.from(frt)[0].innerText);