Table of contents
1.
Introduction
2.
HTML DOM getElementsByClassName() Method
3.
Syntax
4.
Parameters
4.1.
className
5.
Examples
5.1.
Example 1: Changing Text Content
5.2.
JavaScript
5.3.
Example 2: Toggling Classes
5.4.
JavaScript
6.
Supported Browsers
6.1.
Google Chrome
6.2.
Mozilla Firefox
6.3.
Internet Explorer
6.4.
Safari
6.5.
Opera
7.
Frequently Asked Questions
7.1.
Can getElementsByClassName() select elements with multiple classes?
7.2.
How does getElementsByClassName() differ from querySelectorAll()?
7.3.
Is the collection returned by getElementsByClassName() live?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Document getelementsbyclassname

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Understanding how to efficiently find & manipulate elements is crucial for anyone diving into web development. One powerful tool in the arsenal of a web developer is the getElementsByClassName() method provided by the Document Object Model (DOM) in HTML. 

Document getelementsbyclassname

This article aims to unfold the intricacies of this method, guiding you through its syntax, usage, & its compatibility across different browsers. By the end, you'll grasp how to leverage getElementsByClassName() to select HTML elements with ease, enhancing your scripting prowess.

HTML DOM getElementsByClassName() Method

At its core, the getElementsByClassName() method is a DOM functionality that enables web developers to select HTML elements based on their class attribute. This method returns a live HTMLCollection of all elements that share the specified class name, making it a go-to choice for tasks involving bulk element manipulation or retrieval.

This method shines in scenarios where elements are grouped under a common class for styling or scripting purposes. For instance, if you have a set of paragraphs meant to be styled similarly & you need to dynamically change their content or style via JavaScript, getElementsByClassName() becomes incredibly handy.

To effectively use this method, it's essential to understand its behavior & limitations. Unlike an ID selector that targets a unique element, class names can be shared among multiple elements, thus returning a collection rather than a single element. This characteristic necessitates iteration over the returned collection when you need to work with individual elements.

Syntax

The syntax for getElementsByClassName() is straightforward yet powerful, designed to cater to the needs of dynamic webpage manipulation. It's expressed as:

document.getElementsByClassName(className)


Here, className represents the class name or names you're targeting within your HTML document. It's crucial to note that this method is case-sensitive, meaning that myClass and MyClass would be considered different classes.

One interesting aspect of this method is its ability to accept multiple class names, separated by spaces. For example, getElementsByClassName('class1 class2') would return elements that have both class1 and class2 in their class attribute. This feature adds a layer of flexibility, allowing for more precise element selection based on multiple class criteria.

The method is called on a document or any element, offering flexibility in scoping the search. Calling it on document searches the entire document, while calling it on a specific element restricts the search to the descendants of that element, enabling more localized selections.

Parameters

The getElementsByClassName() method is simple in its requirement, taking just one parameter:

className

 A string representing the class name or names you wish to match against. This is where you specify the class or classes of the elements you're targeting. The method will return all elements that have a class attribute that matches this string.

The beauty of this parameter lies in its flexibility. You can specify a single class name or multiple class names. When multiple class names are provided, separated by spaces, the method returns elements that have all the specified classes. For instance, if you use getElementsByClassName('btn active'), it will return elements that have both btn and active classes.

It's important to remember that the className parameter is sensitive to whitespace and case. This means that getElementsByClassName('btnActive') and getElementsByClassName('btnactive') would yield different results, as would getElementsByClassName('btn active') and getElementsByClassName('btn active') due to the extra space in the latter.

This parameter's straightforward nature makes getElementsByClassName() an accessible method for developers to quickly select elements by their class, enhancing the dynamism and interactivity of web pages.

Examples

To illustrate the practical application of getElementsByClassName(), let's walk through some examples that demonstrate how to use this method effectively in various scenarios.

Example 1: Changing Text Content

Imagine you have multiple paragraphs on your webpage designated for user notifications, all assigned the class user-notification. To update all these paragraphs to display a new message, you could use the following code:

  • JavaScript

JavaScript

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CN</title>
</head>

<p class="user-notification">Old Notification 1</p>

<p class="user-notification">Old Notification 2</p>

<script>

   var notifications = document.getElementsByClassName('user-notification');

   for(var i = 0; i < notifications.length; i++) {

       notifications[i].textContent = 'New Notification!';

   }

</script>

</body>

</html>
You can also try this code with Online Javascript Compiler
Run Code

Output

output

In this example, getElementsByClassName('user-notification') fetches all paragraphs with the class user-notification. The loop then iterates through the returned collection, updating the textContent property of each paragraph to 'New Notification!'.

Example 2: Toggling Classes

Suppose you want to toggle a class active for all elements with the class menu-item when a button is clicked. This could be part of a navigation menu where you highlight the active menu item:

  • JavaScript

JavaScript

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CN</title>

</head>

<div class="menu-item">Home</div>

<div class="menu-item">About</div>

<div class="menu-item">Contact</div>

<button onclick="toggleActive()">Toggle Active Class</button>

<script>

   function toggleActive() {

       var items = document.getElementsByClassName('menu-item');

       for(var i = 0; i < items.length; i++) {

           items[i].classList.toggle('active');

       }

   }

</script>

</body>

</html>
You can also try this code with Online Javascript Compiler
Run Code

Output

output


Here, getElementsByClassName('menu-item') selects all div elements with the menu-item class. The toggleActive function then uses a loop to toggle the active class on each element, making use of the classList.toggle method.

These examples demonstrate the versatility and power of getElementsByClassName() in manipulating and interacting with HTML elements based on their class attributes.

Supported Browsers

Understanding which browsers support the getElementsByClassName() method is crucial for ensuring that your web applications function correctly across different environments. Fortunately, this method enjoys broad support across all modern web browsers, making it a reliable tool in a developer's toolkit.

Here's a brief overview of its compatibility:

Google Chrome

Supported since version 1, ensuring almost universal compatibility given Chrome's widespread usage.

Mozilla Firefox

Available from version 3, covering a significant portion of Firefox's user base.

Internet Explorer

Supported from version 9, although it's worth noting that earlier versions of IE are still in use, so fallback strategies may be needed for full compatibility.

Safari

Present since version 3.1, which encompasses the vast majority of Safari versions in use today.

Opera

Integrated from version 9.5, ensuring Opera users can also benefit from this method.

Given this wide support, getElementsByClassName() can be confidently used in projects targeting a general audience. However, for applications that need to support older browsers, especially versions of Internet Explorer before 9, alternative approaches such as getElementsByTagName() combined with manual filtering by class name might be necessary.

This broad compatibility underscores the utility of getElementsByClassName() in modern web development, allowing for efficient element selection and manipulation across a wide array of web projects.

Frequently Asked Questions

Can getElementsByClassName() select elements with multiple classes?

Yes, you can select elements that have multiple classes by providing a space-separated list of class names as the parameter. For example, getElementsByClassName('class1 class2') selects elements with both class1 and class2.

How does getElementsByClassName() differ from querySelectorAll()?

While both methods can select elements with a specified class, querySelectorAll() is more versatile, allowing for complex CSS selectors. However, getElementsByClassName() is faster for class-specific selections and returns a live HTMLCollection.

Is the collection returned by getElementsByClassName() live?

Yes, the HTMLCollection returned by getElementsByClassName() is live, meaning it automatically updates as the DOM changes. This is important to keep in mind when manipulating DOM elements.

Conclusion

The getElementsByClassName() method is a staple in web development for selecting elements by their class names. Its simplicity, combined with the power to select multiple elements and support in all modern browsers, makes it an indispensable tool. Through practical examples, we've seen how it can be used to manipulate the DOM dynamically, enhancing the interactivity and functionality of web pages.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass