Dump "document.write" ASAP

How to get rid of "bad" coding habits.

Table of contents

To get some random info quickly on your webpage I used document.write until I came across this article here from Mozilla: TL;DR. Then I realized I had to get rid of this behavior quickly and find another way to achieve the same, and here's one way of doing so.

This is how I did it in the "old" days:

<!--random refresh number generator-->
<div class="fixedRandom">
    <script>
        document.write("refresh-id:");
        document.write(Math.floor(Math.random() * (1000000000000000000 + 1)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."));
    </script>
</div>

To give some context, the result is a unique generated ID every time the webpage refreshes, which looks like this:

It's a very small almost hidden line, 14pts in a grey color, with a fixed font.

"innerHTML" To The Rescue

To get the same result with a different approach I used innerHTML TL;DR innerHTML.

So this is how I do it now:

<!--random refresh number generator-->
<div class="fixedRandom" id="refreshId">
    <script>
        document.getElementById("refreshId").innerHTML = "refreshId:" + Math.floor(Math.random() * (1000000000000000000 + 1)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    </script>
</div>

With this new approach, the result is identical.