-1
function greet () {
    console.log ("Hi there!");
}
function addButton () {
document.createElement("[wanted_HTML_tag_here]");
}

There is separate HTML document. It has a button that calls the function addButton() upon being pressed. Said function has to create a new element and append it to the element. Pressing this new button has to call the function greet().

I try with [element_name].setAttribute("[attribute]", "[attribute_value]") but useless Also trying document.[element_to_append_into].appendChild([element_being_added]); but same

Tom
  • 1
  • see this SO answer https://stackoverflow.com/questions/3316207/add-onclick-event-to-newly-added-element-in-javascript – Anand Sowmithiran Jan 25 '22 at 13:17
  • this [answer](https://stackoverflow.com/a/7707095/14973743). You should really search the SO, rather than posting new questions. – Anand Sowmithiran Jan 25 '22 at 13:18
  • Does this answer your question? [Creating Dynamic button with click event in JavaScript](https://stackoverflow.com/questions/7707074/creating-dynamic-button-with-click-event-in-javascript) – Anand Sowmithiran Jan 25 '22 at 13:19
  • Please add an actual [mcve] (+ [How do I format my posts using Markdown or HTML?](https://stackoverflow.com/help/formatting)) – Andreas Jan 25 '22 at 13:24

1 Answers1

1

Here's a complete working example (it is one way of doing it):

<html lang="en">
<body>
  <button id="btn">Create Button</button>
</body>

<script>
  function greet() {
    console.log('Hi there')
  }

  function addButton() {
    const button = document.createElement('button')
    const buttonTextNode = document.createTextNode('Click')
    button.appendChild(buttonTextNode)
    button.onclick = greet
    document.body.appendChild(button)
  }

  // get the button that creates other buttons
  const buttonCreator = document.getElementById('btn')
  buttonCreator.onclick = addButton
</script>
</html>