Q:

How to get element by class name in JavaScript

0

How to get element by class name in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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">
<head>
<meta charset="utf-8">
<title>Select Element by Class in JavaScript</title>
<style>
    .box{
        height: 50px;
        background: #ddd;
        margin: 20px;
    }
    .box.bordered{
        border: 5px solid #333;
    }
</style>
</head>
<body>
<div class="box"></div>
<div class="box bordered"></div>
<div class="box"></div>
<div class="box bordered"></div>
<div class="box"></div>

<script>
    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";
</script>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to detect enter key press on keyboard using jQ... >>
<< How to determine if variable is undefined or null ...