Adding an Element then repositioning within HTML

Hi, I’m having a hard time getting this to work correctly, I can’t find the answer anywhere. I added a greeting that says Good Morning, Afternoon, evening depending on the time of day. For some reason it’s showing up at the bottom where my script tags are and not at the h3 element where it should be. What have I done wrong?
This is the code.

var today = new Date();
var hourNow = today.getHours();
var greeting;

if (hourNow > 18) {
    greeting = 'Good evening!';
} else if (hourNow > 12) {
    greeting = 'Good afternoon!';
} else if (hourNow > 0) {
    greeting = 'Good morning!';
} else {
    greeting = 'Welcome!';
}

document.write('<h3>' + greeting + '</h3>');

Hi @cliftonhutch, well document.write() just writes to the document stream – very much like any old write, print or echo construct in other languages. If you want to modify some existing DOM elements instead, you’d first need to get a reference to that element; then you can change its text content:

// Get the (first) h3 element on the page
var myHeading = document.querySelector('h3')
// Change its text content to the greeting
myHeading.textContent = greeting

Hi @cliftonhutch,

There are several ways to select & update a tag in HTML from JS. Check out this

https://plainjs.com/javascript/selecting/

So, If you use getElementById, the code will look like this

Thanks a bunch, That worked like a charm!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.