How to get element by class name in JavaScript

  1139 views   2 years ago Javascript

Use the getElementsByClassName() method

You can use the getElementsByClassName() to get or select the elements by their class attribute value in JavaScript. This method returns an array of matched elements, because more than one element on the page can have the same class. Let's check out an example:

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Select Element by Class in JavaScript</title>
        height: 50px;
        background: #ddd;
        margin: 20px;
        border: 5px solid #333;
    <div class="box"></div>
    <div class="box bordered"></div>
    <div class="box"></div>
    <div class="box bordered"></div>
    <div class="box"></div>
        var boxes = document.getElementsByClassName("box");
        // Select first box and style it with red background
        boxes[0].style.background = "red";
        /* Select elements having both "box" and "bordered" class 
        and style them with yellow background */
        var borderedBoxes = document.getElementsByClassName("box bordered");
        for(var i = 0; i < borderedBoxes.length; i++){
            borderedBoxes[i].style.background = "yellow";
        // Select last element and style it with green background
        boxes[boxes.length - 1].style.background = "green";


Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]