Retrieving All Elements Inside the Body Tag Using Pure JavaScript: Methods and Implementation Details

Dec 08, 2025 · Programming · 9 views · 7.8

Keywords: JavaScript | DOM traversal | getElementsByTagName

Abstract: This article provides an in-depth exploration of methods to obtain all elements within the HTML body tag using pure JavaScript. By analyzing the implementation principles, performance differences, and application scenarios of two core techniques—document.body.getElementsByTagName("*") and document.querySelectorAll("body *")—it explains DOM traversal mechanisms, selector syntax, and strategies for handling nested elements. Code examples demonstrate how to achieve efficient element collection without framework dependencies, along with best practices for real-world development.

DOM Traversal Fundamentals and Body Element Location

In web development, accurately retrieving all elements within a specific area of an HTML document is a common requirement, especially in pure JavaScript environments without relying on third-party frameworks like jQuery. The DOM (Document Object Model) of an HTML document has a tree-like hierarchical structure, where the <body> tag serves as the primary container for document content, encompassing all visible page elements. To obtain all elements inside the body, it is essential to understand the DOM hierarchy: <body> is a child node of <html>, while other page elements (e.g., <div>, <p>, <span>) exist as descendant nodes of the body, potentially forming multi-level nested structures.

Core Method: Utilizing getElementsByTagName

Based on the best answer from the Q&A data (score 10.0), the most direct and efficient approach is to use document.body.getElementsByTagName("*"). This single line of code calls the getElementsByTagName method on the body element with the wildcard "*" as a parameter, returning an HTMLCollection object that contains all tag elements within the body. It works by traversing all descendant elements of the body node, including those at any nesting level. For example, in a simple HTML page:

<body>
  <div>
    <p>Sample text</p>
  </div>
  <span>Another element</span>
</body>

After executing var elems = document.body.getElementsByTagName("*");, elems will include the <div>, <p>, and <span> elements. This method avoids using document.all (which is deprecated and returns elements from the entire document, including non-body content like scripts), ensuring result precision. From a performance perspective, getElementsByTagName is part of the native DOM API and is generally faster than selector-based queries, as it directly manipulates the DOM tree without involving CSS parsing.

Supplementary Method: Flexible Application of querySelectorAll

As a supplementary reference (score 3.7), document.querySelectorAll("body *") offers an alternative implementation. This method uses CSS selector syntax, where "body *" selects all descendant elements of the body element (with the asterisk * as a universal selector). Similar to getElementsByTagName, it returns all nested elements, but the result is a NodeList object instead of an HTMLCollection. A code example is as follows:

var elements = document.querySelectorAll('body *');

If only the immediate child elements of the body (i.e., first-level descendants) are needed, document.querySelectorAll('body > *') can be used, where the > symbol specifies a parent-child relationship. This approach is more flexible, allowing for complex CSS selectors, but may have slightly worse compatibility in some older browsers and slightly lower performance than getElementsByTagName due to the need to parse the selector string.

Implementation Details and Code Examples

To more clearly demonstrate the practical application of these methods, here is a complete JavaScript code example that shows how to retrieve all elements inside the body and perform operations:

// Method 1: Using getElementsByTagName
function getAllElementsMethod1() {
    var allElements = document.body.getElementsByTagName("*");
    console.log("Total number of elements: " + allElements.length);
    for (var i = 0; i < allElements.length; i++) {
        console.log("Element " + i + ": " + allElements[i].tagName);
    }
    return allElements;
}

// Method 2: Using querySelectorAll
function getAllElementsMethod2() {
    var allElements = document.querySelectorAll('body *');
    console.log("Total number of elements: " + allElements.length);
    allElements.forEach(function(element, index) {
        console.log("Element " + index + ": " + element.tagName);
    });
    return allElements;
}

// Call the functions
getAllElementsMethod1();
getAllElementsMethod2();

In this example, getAllElementsMethod1 uses getElementsByTagName, which returns a dynamic HTMLCollection that updates with DOM changes; whereas getAllElementsMethod2 uses querySelectorAll, returning a static NodeList that captures a snapshot of the DOM at the time of the call. Developers should choose based on specific needs: if real-time updates are required, getElementsByTagName is preferred; for one-time queries or complex selections, querySelectorAll may be more suitable.

Performance Analysis and Best Practices

In real-world projects, performance is a key factor in method selection. Tests show that getElementsByTagName("*") generally executes faster than querySelectorAll("body *"), as it avoids the parsing overhead of the CSS engine. For instance, on a page with 1000 elements, the former might be 10-20% faster. However, this difference is less noticeable in most modern browsers unless dealing with extremely large DOMs. Best practices include:

In summary, retrieving all elements inside the body using pure JavaScript is a fundamental yet crucial skill. Mastering the core usage of getElementsByTagName and querySelectorAll enables developers to handle DOM operations efficiently, reducing reliance on external frameworks.

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.