0

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.

aynber
  • 22,380
  • 8
  • 50
  • 63
Sulty
  • 13
  • 3
  • 2
    https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents – Teemu Feb 23 '23 at 13:16
  • 2
    Why does it look like you ran your script through an HTML sanitizer? This script won't work. – aynber Feb 23 '23 at 13:18
  • I just need to know if there is a way to replace document.write with another thing. – Sulty Feb 23 '23 at 13:23
  • The HTML must have been loaded for `document.body.append` or `document.body.innerHTML` to work, otherwise the DOM doesn't exist. So you need to add your script after the HTML or use set up a listener for the load event: https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event – Rickard Elimää Feb 23 '23 at 13:28

1 Answers1

0

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!