On a submit, greet user

Hello hope all is well,

So I am trying to greet a user with “Hello name” when they enter their name and click submit. Unfortunately, each click appends another “Hello name” instead of overwriting the previous h2 tag in main.


// When the page finishes loading.
window.onload = function () {
  // Initializing variables.
  var button_submit = document.getElementById("submit_section");
  
  button_submit.onclick = function () {
    // Initializing variables.
    var greeting = "Hello "; 
    var main = document.getElementById("main");
    var output = document.createElement("h2");
    var text_section = document.getElementById("text_section");
    var name = text_section.value;
    
    // Program logic
    greeting += name;
    output.innerHTML = (greeting);
    
    // Output the message.
    main.appendChild(output);
  };
};

The problem is at the output message part, I’m not sure what to do differently.
Thanks,
Polyhedra (Dan)

Currently your appendChild is adding a new one each time that code runs.

What you can do instead, is to check if its already on the page, and if it is to then use that one.


function addGreeting(target) {
    var h2 = ...
    h2.classList.add('greeting');
    target.appendChild ...
}

var output = document.querySelector('.greeting');
if (!output) {
    output = addGreeting(main);
}
...