0

Getting type error in console:

Uncaught TypeError: Cannot read property 'addEventListener' of null

after clicking the "Click" button. How can I fix this?

document.getElementById("btn").addEventListener("click", function(){
  document.getElementById("para").innerHTML("This is text");
});
<ul id="myList">
  <li>item1</li>
  <li>item 2</li>
</ul>
<button id="btn">Click </button>
<form name="myForm">
  Select output mode: <input type="radio" name="output" value="printer" checked /> Printer
  <input type="radio" name="output" value="scanner" /> Scanner
</form>
Jesse
  • 3,093
  • 6
  • 22
  • 35
CrackCode
  • 17
  • 2
  • 3
    Check your browser console, it'll tell you. You're trying to assign a listener to an element before the element's been created in the HTML. Put the script in a separate file and give it the `defer` attribute. Also, you have no jQuery here, please tag your questions appropriately. – CertainPerformance May 16 '18 at 06:45
  • You should have an error like `VM99:1 Uncaught TypeError: Cannot read property 'addEventListener' of null` in your console – Arun P Johny May 16 '18 at 06:46
  • One way to fix this is to move your script to the bottom of `body` tag – Arun P Johny May 16 '18 at 06:47
  • In addition to @CertainPerformance's note: It's invalid HTML to have a `script` tag as the direct child of the `html` tag. `script` tags must be in `head` or `body`. Putting your script tag at the very end of `body`, just prior to the closing `

    ` tag, is best unless you have a reason to do something else, and it would correct the first problem above. The second problem is that `innerHTML` isn't a function, it's a property.

    – T.J. Crowder May 16 '18 at 06:47

1 Answers1

0

You need to use document.getElementById("para").innerHTML = "This is text"; as innerHTML is not a function but a property of the getElementById().

document.getElementById("btn").addEventListener("click", function(){
    document.getElementById("para").innerHTML = "This is text";
})
<p id="para"> </p>
<ul id="myList">

    <li>item1</li>
    <li>item 2</li>
</ul>
<button id="btn">Click </button>
<form name="myForm">
    Select output mode: <input type="radio" name="output" value="printer" checked /> Printer
    <input type="radio" name="output" value="scanner" /> Scanner

</form>
Ankit Agarwal
  • 28,439
  • 5
  • 29
  • 55