HomeMethod

Knowledge

Web VitalsTechniquesSnippetsAnswersImpactsBottlenecks

Count DOM elements

  • Performance

Keep an eye on the DOM nodes count to avoid ending up with a number that might start hindering the page’s performance.

As a reminder, the more DOM nodes increase, the more impact in will have in DOM manipulation.

count-dom-elements.js
/**
 * Count DOM Elements
 *
 * Count visible DOM elements within a container. Excludes non-visual tags
 * (meta, link, style, script, noscript) since they don't contribute to
 * rendering cost. Useful for diagnosing DOM bloat that degrades performance.
 *
 * Usage: Run in browser console. Pass `document` for the full page
 *        or any element to count within a specific container.
 *
 * @category performance
 * @language javascript

 *
 * @author Adame Dahmani https://adame.io
 * @support Support my family project: https://adame.io/fundraiser
 */
function snippet_count_dom(element) {
    if (!element) {
        console.error(`Element ${element} not found.`);
        return -1;
    }
    const nodes = element.querySelectorAll("*:not(meta):not(link):not(style):not(script):not(noscript)");
    return nodes.length;
}

snippet_count_dom(document);

Change the document inside snippet_count_dom() to count the number of nodes inside a specific parent element.

Support our family now