-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

4

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.