javascript
  1. javascript-getelementsbyclassname

JavaScript getElementsByClassName()

Heading

JavaScript getElementsByClassName() is a method that returns a collection of all elements in the document with a specified class name.

Syntax

document.getElementsByClassName(class)

Example

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript getElementsByClassName() Example</title>
  </head>
  <body>
    <div class="container">
      <p class="paragraph">This is the first paragraph.</p>
      <p>This is the second paragraph.</p>
    </div>
    <script>
      const paragraphs = document.getElementsByClassName("paragraph");
      console.log(paragraphs);
    </script>
  </body>
</html>

Output

HTMLCollection [ p.paragraph ]

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript getElementsByClassName() Example</title>
  </head>
  <body>
    <div class="container">
      <p class="paragraph">This is the first paragraph.</p>
      <p>This is the second paragraph.</p>
    </div>

    <!-- JavaScript code -->
    <script>
      // Use getElementsByClassName to select elements with the class "paragraph"
      const paragraphs = document.getElementsByClassName("paragraph");

      // Log the selected elements to the console
      console.log(paragraphs);
    </script>
  </body>
</html>
Try Playground

Explanation

The getElementsByClassName() method searches for all elements in the document that have the specified class name and returns a collection (an array-like object) of those elements. The method accepts only one argument, which is the class name to search for.

In the above example, const paragraphs = document.getElementsByClassName("paragraph"); selects the element with class paragraph and stores it in a variable called paragraphs. The resulting collection is then logged to the console, which will contain a single element.

Use

The getElementsByClassName() method is useful for selecting and manipulating multiple elements with a shared class name. This can be particularly helpful when working with complex, multi-layered designs where you need to apply the same styles or behaviors to many different elements at once.

Important Points

  • The getElementsByClassName() method is case-sensitive.
  • The method returns a collection of elements, even if there is only a single matching element.
  • The collection returned by this method is live, meaning that if more elements are added to or removed from the document, the collection will be updated accordingly.

Summary

  • getElementsByClassName() is a JavaScript method that returns a collection of all elements with a specified class name.
  • The method accepts only one argument - the class name to search for - and is case-sensitive.
  • The resulting collection is a live object that can be manipulated dynamically.
Published on: