1

I would like help to update this date.js code to remove the document.write statements as it is now obsolete

 if (Date.parse(document.lastModified) != 0) {
  var modiDate = new Date(document.lastModified);
  var monthName = new Array("January", "February", "March", "April", "May", 
   "June", "July", "August", "September", "October", "November", "December");
  document.write(monthName[modiDate.getMonth()] + " ");
  document.write(modiDate.getDate() + ", " + modiDate.getFullYear());
  }

What do I put in place of document.write(...... please

the javascript code produces a (File) Updated on September 12, 2019 at the bottom of the web page via this code snipit

 <p>Updated <script type="text/javascript" src="/public/jsscripts/date.js"> </script>

Thanks Mark

3 Answers3

1

You can use insertAdjacentHTML, which is the closest equivalent replacement of document.write together with currentScript to get the HTML element of the script, that's being evaluated.

<p>Updated
  <script>
    var modiDate = new Date(document.lastModified);
    var monthName = new Array("January", "February", "March", "April", "May",
      "June", "July", "August", "September", "October", "November", "December");
    var text = monthName[modiDate.getMonth()] + " ";
    text += modiDate.getDate() + ", " + modiDate.getFullYear();
    document.currentScript.insertAdjacentHTML('afterend', text);
  </script>
</p>
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38
0

Something like this maybe.

It'll update all elements with the class documentLastModified.

<p>Updated <span class="documentLastModified" /></p>

<script>
var modiDate = new Date(document.lastModified);
[].slice.call(document.querySelectorAll('.documentLastModified')).forEach((el) => {
  el.innerHTML = modiDate.toDateString();
});
</script>
AKX
  • 152,115
  • 15
  • 115
  • 172
0

Use getElementById and toLocaleDateString

// date.js

document.getElementById('updated-date').textContent = new Date().toLocaleDateString('en-US', { /* new Date(document.lastModified)... */
  month: 'long',
  day: 'numeric',
  year: 'numeric'
})
<p>Updated <span id="updated-date"></span></p>

<!-- end of body 
<script type="text/javascript" src="/public/jsscripts/date.js">-->
User863
  • 19,346
  • 2
  • 17
  • 41