Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid document.write

I’ve a script and I want to use another sentence instead of document.write()
as you can see at the last line
document.write(convertTimestamp(&quot;<data:post.timestamp/>&quot;));

<script>
    function convertTimestamp(timestamp) {
    var currentTime = new Date();
    var convertedTimestamp = new Date(timestamp);
    var offset = -new Date().getTimezoneOffset();
    convertedTimestamp = new Date(convertedTimestamp.getTime() + offset * 60 * 1000);
    var timeDifference = currentTime - convertedTimestamp;

    var seconds = Math.floor(timeDifference / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);


    if (seconds &lt; 60) {
    return seconds + &#39; seconds39;;
} else if (minutes &lt; 60) {
    return minutes + &#39; mins &#39;;
} else (hours &lt; 24) {
    return hours + &#39; hours&#39;;
}
}
    document.write(convertTimestamp(&quot;<data:post.timestamp/>&quot;));
</script>

Can I use other words instead of document.write?
I saw a recommendation to use
document.body.append
or
document.body.innerHTML
but I don’t know how to apply it on my code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A better way and essentially a different way to do this is:

Create the element:

let elementToAdd = document.createElement('p');
elementToAdd.innerHTML = `Your expression here`;
document.body.appendChild(elementToAdd)

Add content to the element:

elementToAdd.innerHTML = convertTimestamp(&quot;<data:post.timestamp/>&quot;)

Append that element to the body:

document.body.appendChild(elementToAdd)

This will result in increased code but it’ll help you scale it better in future and is more obvious to the naked eye.

Hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading