JavaScript Code


JavaScript – Find Elements by Class Name


Tutorials using JS

Find Elements by Class Name

to find elements in the document that has a given class name, use Document.getElementsByClassName() function

Syntax

The syntax of getElementsByClassName() function is

document.getElementsByClassName("class_name")

where

  • document object is the root node of the HTML document
  • getElementsByClassName is the function name
  • class_name is the value of attribute class for the elements that we are searching in the document

the function call returns a NodeList object which is like an array of elements, that has the given class name

Examples

1. find elements whose class name is note

in the following document, we have three paragraphs. when user clicks on Click Me button, we find the elements by class name 'note' and change their background color to yellow

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Find Elements by Class Name</h2>
<button id="myBtn">Click Me</button>
<p>This is a paragraph.</p>
<p class="note">This is another paragraph.</p>
<p class="note">This is third paragraph.</p>

<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
    //get all the elements whose class name is 'note'
    const notes = document.getElementsByClassName('note');
    for ( let i = 0; i < notes.length ; ++i) {
        notes[i].style.background = 'yellow';
    }
});
</script>

</body>
</html>


Copyright @2022