Skip to main content

JavaScript: Recursively Retrieve All Nested DOM Elements (Snippet)

Hi. 🙂

Let's name the function as crawlElements.

The function above will return a flat array of DOM elements.

That's it then. The description and how to use it are included in the snippet.

R_T

What's That For?

I, personally, did it for dynamic injection of new elements into a previously rendered container. To achieve even spacing, I need to gather all of the nested elements in that container, then calculate the index position. Surely, it can be limited to a certain depth — but that's the main idea. In this, "everyone categorised as DOM element inside that confinement is censused".

Other notable proper uses:

  • Accessibility Audits

    Gather all elements to check for missing aria-*, alt, or role attributes. Make your page less of a chaos for screen readers. But of course, a chaotic page is hilarious. Screen readers shall stutter, we shall... laugh.
  • Analytics Instrumentation

    Recursively tag or wrap elements with data-* attributes for tracking purposes. Like we glue lit Molotov cocktails to places: wall, ceiling, bathroom. Hm.. This one, is properly burnt. Scentful.
  • Sanitising Content

    Crawl user-generated DOM trees to strip or validate elements before rendering (e.g., stripping script or inline styles). Like we put our clothes on after done being naked. 🤣 I have no better analogy.
  • Lazy-loading Enhancements

    Detect all img or video tags and inject lazy-loading or intersection observers. Indeed.

Until Next Time

By default, I don't use a semicolon to end a line when typing JavaScript, and I set my JS linter and prettier to be that too. But because we want to look like C 😂, well, semicolon it is. It was from my habit in Python back then. Hi, Python. (Wave.)

By golly, Python, the core changes, aye? Google App Engine (GAE) is... hm, well, hm, well, here's a gate, a gate is here. People with Python 2.7 applications deployed on GAE are 😠😡 — 🤣 what an awkward jest. We can use container though, like Google's Cloud Run, Kubernetes Engine, Compute Engine. Or, AWS container... Or, Azure. Or, not.

Or, stay on GAE and migrate the squiggly to Go(lang), and goes bonkers. (I) Here's the build version. Run it, please. (👀 Staring at logs.) (GAE) Uh, what build version? Where is main()? Error nil pointer dereference. (I) 🤦

(I) Very well, Node.js it is then. (GAE) Welcome, have a seat. (I) Ah.

Node.js derailment caused by semicolon remark and this post is about a JS snippet for crawling nodes recursively. Recursion. 🏆

Cheers. 🙂

Last modified on

Comments

Monkey Raptor uses cookies or biscuits 🍪 for analytics, functionality, and advertisements. More info in Privacy Policy