Multiple Methods for Getting DOM Elements by Class Name in JavaScript and Their Implementation Principles

Nov 13, 2025 · Programming · 8 views · 7.8

Keywords: JavaScript | DOM Manipulation | Class Name Selection | getElementsByClassName | querySelectorAll | Browser Compatibility

Abstract: This article provides an in-depth exploration of various methods for retrieving DOM elements by class name in JavaScript, including traditional element traversal, the modern getElementsByClassName method supported by contemporary browsers, and the querySelectorAll approach. It thoroughly analyzes the implementation principles, browser compatibility, and performance characteristics of each method, offering complete code examples and best practice recommendations. By comparing the advantages and disadvantages of different approaches, it assists developers in selecting the most suitable solution based on specific requirements.

Introduction

In web development, dynamically manipulating DOM elements is a common requirement. When there is a need to operate on multiple elements sharing the same class name, traditional methods of retrieving elements by ID become inadequate. This article systematically introduces various technical solutions for obtaining DOM elements by class name in JavaScript.

Traditional Traversal Method

In scenarios involving older browsers or the need to maintain compatibility with legacy versions, class name matching can be achieved by traversing all elements within the document. The core concept of this approach is to check whether the className property of each element includes the target class name.

function replaceContentInContainer(matchClass, content) {
    var elems = document.getElementsByTagName('*'), i;
    for (i in elems) {
        if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ') > -1) {
            elems[i].innerHTML = content;
        }
    }
}

How this method works: First, it uses document.getElementsByTagName('*') to retrieve all elements within the document. It then iterates through each element, checking via string matching whether its class name contains the target class name. Adding spaces before and after the class name ensures exact matching, preventing partial matches.

Native Support in Modern Browsers

With the evolution of web standards, modern browsers provide the native getElementsByClassName method, which returns an HTMLCollection object containing all matching elements.

var elements = document.getElementsByClassName('someClass');

It is important to note that getElementsByClassName returns a live collection. When the DOM changes, the collection automatically updates. This method is well-supported in IE9+ and modern browsers.

CSS Selector Method

The querySelectorAll method offers more powerful selection capabilities, supporting full CSS selector syntax, including class selectors.

function ReplaceContentInContainer(selector, content) {
  var nodeList = document.querySelectorAll(selector);
  for (var i = 0, length = nodeList.length; i < length; i++) {
     nodeList[i].innerHTML = content;
  }
}

ReplaceContentInContainer(".theclass", "HELLO WORLD");

Unlike getElementsByClassName, querySelectorAll returns a static node list that does not automatically update with DOM changes.

Method Comparison and Selection Recommendations

Compatibility Considerations: If support for IE8 and earlier versions is required, the traditional traversal method is the most reliable choice. For projects targeting modern browsers, it is recommended to prioritize getElementsByClassName or querySelectorAll.

Performance Analysis: The traditional traversal method performs poorly when the number of elements is large, as it requires checking each element. getElementsByClassName, being natively implemented by the browser, offers optimal performance. querySelectorAll, while the most feature-rich, has slightly lower performance than getElementsByClassName in simple class name matching scenarios.

Usage Scenarios:

Practical Application Example

The following is a complete example demonstrating how to safely implement cross-browser class name element operations:

function getElementsByClassNameSafe(className) {
    if (document.getElementsByClassName) {
        return document.getElementsByClassName(className);
    } else {
        var elements = document.getElementsByTagName('*');
        var result = [];
        for (var i = 0; i < elements.length; i++) {
            if ((' ' + elements[i].className + ' ').indexOf(' ' + className + ' ') > -1) {
                result.push(elements[i]);
            }
        }
        return result;
    }
}

function replaceContentByClass(className, content) {
    var elements = getElementsByClassNameSafe(className);
    for (var i = 0; i < elements.length; i++) {
        elements[i].innerHTML = content;
    }
}

Conclusion

JavaScript offers multiple methods for retrieving DOM elements by class name, each suited to specific scenarios. When choosing a method, developers should comprehensively consider browser compatibility, performance needs, and functional requirements. With the widespread adoption of modern browsers, native methods like getElementsByClassName and querySelectorAll have become the preferred choices. However, in situations with specific compatibility requirements, the traditional traversal method remains valuable.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.