Search code examples
javascriptvariablesappendchild

display greeting according to current time in appendChild()


I created a h3 within a div and now am trying to display a greeting appropriate for the current time of day. It displays on the play as an h3 but only results in undefined.

Can someone tell me what I am missing or doing wrong that the hours will not calculate?

var h3 = document.createElement("h3");
var d = new Date();
var hour = d.getHours();
var greeting;


function greetCustomer() {
 if (hour > 18) {
   greeting = "Good Evening";
 }
  
 else if (hour > 12) {
   greeting = "Good Afternoon";
 }
  
 else if (hour > 5) {
   greeting = "Good Morning";
 }
  
 else {
   greeting = "Welcome Night Owl";
 } 
  
  document.getElementById("greeting").appendChild(h3);
}

h3.innerHTML = greetCustomer();
<div id="greeting"></div>


Solution

  • You need to return the greeting string from the function.

    You don't need to append the H3 to the DOM in greetCustomer(), that should be done outside the function. And all the time-related variables should be local to the function, since they need to be recomputed every time the function is used.

    var h3 = document.createElement("h3");
    document.getElementById("greeting").appendChild(h3);
    h3.innerHTML = greetCustomer();
    
    function greetCustomer() {
      var d = new Date();
      var hour = d.getHours();
      var greeting;
      if (hour > 18) {
        greeting = "Good Evening";
      } else if (hour > 12) {
        greeting = "Good Afternoon";
      } else if (hour > 5) {
        greeting = "Good Morning";
      } else {
        greeting = "Welcome Night Owl";
      }
      return greeting;
    }
    <div id="greeting"></div>