What is the most effective way to retrieve all child Elements within a parent container?

Is there a way to retrieve all descendant elements within the parent container and store them in an array?

<div class="parent">
    <div class="child1">
        <span class="child2">
            <div class="child3">
                <div class="child4">
                    <span class="child5"></span>
                </div>
                <div class="child6">
                    <div class="class7"></div>
                </div>
            </div>
        </span>

        <div class="child8"></div>
        <span class="child9">
            <div class="child10"></div>
        </span>
    </div>
</div>

I am considering recursion as one of the possible options. Initially, I have access to the parent element.

Answer №1

If you're referring to youngsters, then element instances contain childNodes (which includes non-element children like text nodes) and, on most engines, children (which specifically refers to child elements only). (You've clarified that you mean descendants.)

If by descendants, you can utilize querySelectorAll:

var descendants = theElement.querySelectorAll("*");

All modern browsers, as well as IE8, support querySelectorAll.

This returns a NodeList, which is similar to an array. If you prefer a genuine JavaScript array, you can achieve it using Array.prototype.slice, like so:

var descendants = Array.prototype.slice.call(theElement.querySelectorAll("*"));

Alternatively, you can utilize Array.from (introduced in ES2015, but easy to polyfill):

var descendants = Array.from(theElement.querySelectorAll("*"));

Nowadays, since most environments have made NodeList iterable (and you can easily polyfill it if not), you can also make use of spread notation in an ES2015+ environment:

var descendants = [...theElement.querySelectorAll("*")];

Example:

var descendants = Array.prototype.slice.call(
  document.querySelector(".parent").querySelectorAll("*")
);
descendants.forEach(function(descendant) {
  display(descendant.className);
});
function display(msg) {
  var p = document.createElement('p');
  p.innerHTML = String(msg);
  document.body.appendChild(p);
}
<div class="parent">
    <div class="child1">
        <span class="child2">
            <div class="child3">
                <div class="child4">
                    <span class="child5"></span>
                </div>
                <div class="child6">
                    <div class="class7"></div>
                </div>
            </div>
        </span>

        <div class="child8"></div>
        <span class="child9">
            <div class="child10"></div>
        </span>
    </div>
</div>

Answer №2

For better performance, opt for

theElement.getElementsByTagName("*")
instead of theElement.querySelectorAll("*"). The former is faster and has broader support in older browsers.

The result of this method is an HTMLCollection that behaves like an array. If you need it as a real Array, you can convert it by using:

Array.prototype.slice.call(theElement.getElementsByTagName("*"))

If you require extensive browser compatibility, consider using either jQuery 1.12.4 or picoQuery. PicoQuery is a reimplementation of jQuery where you can choose specific methods using an online builder. In the case mentioned above, no additional methods are needed since selection is included in the core, and the package size is only 1kb when gzipped. PicoQuery is designed for modern browsers but seamlessly switches to jQuery 1.12.4 for older browser support.

Answer №3

const allDescendants = document.querySelector('.parent').querySelectorAll('*');

To begin, locate the desired parent element using any method you prefer, then utilize querySelectorAll() to gather all of its descendant elements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can JavaScript be used to change the style and make a hidden input field vanish from view?

Currently, I am designing a table containing dates along with numerous hidden fields. print "<td"; { $dm=date('Y-m-d',strtotime("+".$i." days", strtotime($m))); print " class=\"overflow\" id=\"$a::$dm\" onclick=\" ...

Struggling to trigger jQuery on postback

I have been searching for a while and experimenting with different solutions from various posts, but I can't seem to make any of them work. Here is the basic idea... I am modifying an existing usercontrol that organizes dynamically generated data into ...

Using JavaScript to Capture a Webpage Element as an Image

Although this question has been asked in the past, I am hoping for updated information since all the answers are from a few years ago. While searching, I came across https://github.com/apollolm/phantasm, which seems to be exactly what I need. However, it ...

Transforming a JSONP request to automatically parse a text response into JSON

If I have the following request $.ajax({ type: "GET", dataType: "jsonp", jsonp: "callback", jsonpCallback: "my_callback", url: my_https_url, headers:{"Content-Type":"text/html; charset=utf-8"}, success: function(data) { ...

The setInterval function continues to execute endlessly even after each interval is three months

I need to remove all expired OTP records every three months. In the file /sheduled-tasks/OTPRecords.js const prisma = require("../services/prisma"); const THREE_MONTHS = 1000 * 60 * 60 * 24 * 90; async function deleteExpiredOTPRecords() { ...

two adjacent elements filling the entire height of the window at 100% dimensions

Is there a way to place two elements side by side, with one of them (the textarea) always being 100% height of the window? I've looked at similar questions here but can't figure out how to make it work. Can you help me with this? html: <div ...

The property 'apply' is trying to be accessed but is undefined and cannot be read

Not being an expert in frontend development, I've hit a roadblock on what seems like a simple issue. I'm attempting to load one set of nodes from a JSON file successfully, but when trying to add new nodes from another JSON file, I encounter this ...

Transferring HTML variables to an Angular Component

I am currently trying to transfer the information inputted into a text-box field on my webpage to variables within the component file. These variables will then be utilized in the service file, which includes a function connected to the POST request I exec ...

Develop a sophisticated multi-page application using create-react-app in conjunction with express.js

While I'm comfortable with back-end work, my front-end programming skills have gotten rusty. I used to work a lot with React, but it's been over a year since I last touched it. Recently, I started a project that requires me to refresh my knowledg ...

Preview and enlarge images similar to the way Firefox allows you to do

When you view an image in Firefox, it is displayed with the following characteristics: Centered within the browser window. Has a height/width that fits within the browser dimensions. Does not resize larger than its maximum size. Remains the same size if ...

Clicking on the parent page prevents the hyperlink inside the iframe from working as expected

I am having an issue with a hyperlink inside an iframe. When I click on it in the parent page, it doesn't work. Here is how it is set up: iframe.html <h1>I'm inner page!</h1> <a id="shared" class="btn" href=&q ...

Guide to implementing 'active' state in Bootstrap 4 using JavaScript on a basic PHP website

A simple website consisting of three pages, designed using Bootstrap 4 framework. I have utilized includes to incorporate header.php and footer.php into the respective PHP pages below. My challenge lies in adding the 'active' class from Bootstrap ...

Crop multiple images using dropzone.js before uploading

Currently, I have integrated Bootstrap with dropzone.js to allow users to upload images via drag & drop. Everything is functioning smoothly, even with the ability to upload multiple images. However, my next goal is to implement image cropping before uplo ...

Incorporating grids for a flickering drag and drop effect in Javascript

I have been working on developing a selection system for a tilemap image where users can select multiple tiles by dragging the mouse to increase the size of the selection container. However, I've noticed a flickering effect while holding down the mous ...

Using Three.js to Showcase Images within a JSON Data Structure

I am currently utilizing version 71 of the library to showcase an image on each side of a 3D object created in Blender. It doesn't matter if different images are used or if one image is repeated. The object is loaded using a load function post its ins ...

Can someone assist me in figuring out why the ShowDetail.html page is not opening after I submit my form?

I'm having trouble getting the shoDetail.html page to open when I submit the code. I even tried entering the complete URL, but it still won't work. Here is the code I am using: <div class="form-group row"> <div class="col-lg-12 col-md-1 ...

Which option's value was recently removed from the fetch command?

I created a function to handle duplicate selections in a select element. It is functioning properly, but I noticed that when I remove an option from the select, my array remains unchanged. If I remove an option, I want my code to detect the value of that ...

Is it possible to dynamically populate a dependent select box using Jinja variables?

I am currently using Flask with Jinja2 templates, and I need assistance in creating dependent select boxes. How can I achieve this using Jinja2 or a combination of JavaScript and Jinja2 variables? For example: On the Python side: @app.route('/&apos ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

trouble with filtering date ranges using Javascript

I am trying to filter the dates between two textboxes. However, I am facing an issue where the date I choose in the second box is not being included. Here is the code for the textboxes: <label for="from">From</label> <input type="text" id ...