Home > Mobile >  Pressing button - call function in JS
Pressing button - call function in JS

Time:08-27

Referring to question posted (link below) before 7 months,

Javascript. Pressing button - call function

I would like to ask why I am getting those 2 errors when executing the code on the compiler of the university. Please note that I have zero control on the code of the html which the compiler react with

Uncaught: TypeError: Cannot set property 'onclick' of null

Uncaught: ReferenceError: createdButton is not defined

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)
  }

  const buttonCreator = document.getElementById('btn')
  buttonCreator.onclick = addButton

CodePudding user response:

These errors are pretty straightforward. The first one is telling you that there is no element with the id of btn in your HTML, hence why it's returning null.

For the second one I don't see where you're calling createdButton, but it's telling you it isn't defined anywhere. If I had to take a guess, either you're calling createdButton before you define it or there's not a variable named createdButton.

CodePudding user response:

Try:

  1. You have no element with id of "btn", try adding the id to the button you want to listen the onclick event.

  2. I wonder why this error is happening: Uncaught: ReferenceError: createdButton is not defined. Because, there are no words about createdButton. Can you give us the full code?

  • Related