0

I know that you can use document.createElement for this but I get a domexception from doing this:

document.createElement("<input onchange='myFunction()' />");

Error:

Uncaught DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('<input onchange='myFunction()' />') is not a valid name.

Do you know how to create an element dynamically with a function?

2 Answers 2

1

You should make it in 3 times :

  • First creating the element
  • Then adding the function
  • Finally adding it to the dom

const myFunction = () => {
  console.log("hello world")
}

const btn = document.createElement('button')
btn.innerText = "MyBtn"
btn.addEventListener('click', myFunction)
document.body.appendChild(btn)

Sign up to request clarification or add additional context in comments.

Comments

0

Sorry I was too quick to ask for help. But this is the answer:

newInput3.onchange = myFunction;

myFunction should not be an actual string.

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.