0

I have a script that displays the date 2 weeks in the future. Everything works correctly, but I'm wanting to clean it up more and make it display in one sentence, rather than broken into two paragraphs. I cannot for the life of me figure out how to do this. Any help will be greatly appreciated.

<script>
var twoWeeksForward = new moment().add(14, 'day');
document.write(twoWeeksForward.format('dddd, MMMM DD, YYYY')); 
</script>

<p style="text-align:center"><i class="fas fa-tshirt"></i>Complete your order now and receive it by </p><span class="date"><p class ="twoWeeksForward">
KLBRTNZ
  • 3
  • 1
  • 1
    `document.write` is [not recommended](https://stackoverflow.com/q/802854/4642212) for DOM manipulations, as it is obsolete, slow and not suitable for any evolving application. See [the documentation about the DOM API on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) and use methods that aren’t discouraged. – Sebastian Simon Feb 13 '21 at 17:52
  • `document.write()` is not your friend; use DOM manipulation functions instead. – PA. Feb 13 '21 at 17:53
  • I get that, but it works for what I use it for. I've tried moment.js, but I can't get that to display how I want it to either. – KLBRTNZ Feb 13 '21 at 17:54
  • and you'll probably never make it fit your needs – PA. Feb 13 '21 at 17:55
  • Use ```document.getElementsByClassName("twoWeeksForward")[0].innerText``` not ```document.write``` – Giacomo Casadei Feb 13 '21 at 17:55
  • @GiacomoCasadei If the script is still above that element, this won’t work. – Sebastian Simon Feb 13 '21 at 17:56

2 Answers2

0

As others said in comments, it's best not to use document.write(). But if you really must use it, you have to put the script inside the <p>. When the page is loading, it writes to the current point in the HTML.

<p style="text-align:center"><i class="fas fa-tshirt"></i>Complete your order now and receive it by </p>
<span class="date">
    <p class ="twoWeeksForward">
    <script>
    var twoWeeksForward = new moment().add(14, 'day');
    document.write(twoWeeksForward.format('dddd, MMMM DD, YYYY')); 
    </script>
    </p>
</span>
Barmar
  • 596,455
  • 48
  • 393
  • 495
0

Try manipulating the innerText of the paragraph you'd like to add the text to. For example, for a paragraph with id="my-p", you could use:

document.getElementById("my-p").innerText += twoWeeksForward.format('dddd, MMMM DD, YYYY');

This way you will not need a new element every time you update text with javascript.

Run_Script
  • 2,146
  • 2
  • 10
  • 24