0

Stumbling upon a Javascript DOM Elements Counter here and here (courtesy of lingtalfi) I want to speed up my website. Apparently the number of, the length of and the depth of DOM elements seems to have an impact on speed. I want to count the DOM overhead and show it in the HTML without a need for a keypress. This could be done 5 seconds after the page has loaded to not interfere with the speed of the website.

Method 1: Alert Popup Box

 <a href="
    javascript: (function()
       {alert(document.getElementsByTagName('*').length);
       }());
    ">Count DOM nodes of a page
 </a>

Method 2: Just Write in HTML

 <script>
      (function() {
       document.write(document.getElementsByTagName('*').length);
      }());
 </script>

On my site the first method popups 814, while the second method writes 142. Quite a difference!

My question is: Is there a way to (delay and) output the correct number of DOM elements just in HTML without the need to click on a popup to count the DOM elements?

(function () {document.write(document.getElementsByTagName('*').length); }());
body {
font-size: 5em;
font-family: "Arial";
}
Sam
  • 15,254
  • 25
  • 90
  • 145

1 Answers1

1

I am absolutely not sure about your question! Are you searching for something like that ?

Please keep in mind that the number in the demo may be larger than the code shows. Stack Overflow adds more elements behind the scenes.

document.addEventListener("DOMContentLoaded", () => {
    setTimeout(() => {
        document.querySelector('aside').textContent = document.getElementsByTagName('*').length;
    }, 5000)
});
<html>
    <head>
    </head>
    <body>
        <div class="header">
            <div class="pages">
                <div class="page">index</div>
                <div class="page">contact</div>
            </div>
        </div>
        <div class="main-content">
            <div class="section-1">

            </div>
            <div class="section-2">

            </div>
            <div class="section-3">

            </div>
        </div>
        <footer>

        </footer>
        <aside></aside>
    </body>
</html>
Jonathan
  • 131
  • 3
  • Yess thats it! That did the trick, it counts 814 after 5 seconds. Dreamweaver gives an error on the syntax?! Also it puts this number on top of the HTML "outside" the website. Is there a way that it could just write the output into a specific area within the HTML say inside ``? – Sam Jun 07 '22 at 14:10
  • 1
    @Såm Yes of course! I changed the demo for your case. – Jonathan Jun 07 '22 at 14:17