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.


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.
  • Analytics Instrumentation

    Recursively tag or wrap elements with data-* attributes for tracking purposes.
  • Sanitising Content

    Crawl user-generated DOM trees to strip or validate elements before rendering. For example, stripping script or inline styles.
  • Lazy-loading Enhancements

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

Bye. 👋

Comments

Monkey Raptor uses cookies for analytics, advertisements, and functionality. More info on Privacy Policy