Javascript event listener

I have the following code in JavaScript.

'use strict';

document.body.append(document.createElement('textarea'));

document.body.append(document.createElement('button'));

let btnClick = document.getElementById('button');

function inClick() {

let str = 'abc';

console.log(str);

}

btnClick.addEventListener('click', inClick);

I am getting the following error when execting this script.

Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’).

I am unable to add an event listener when the button is clicked.

Implies that there is no element with the ID “button”.

Note that an id is an attribute, not an element type. <button> can be found by getElementsByTagName, but to find something with id button, it would have to be <something id="button">

1 Like

I suggest:

document.body.append(document.createElement('textarea'));
let btn = document.createElement('button');
btn.innerText = "Click Me";
document.body.append(btn);

function inClick() {
console.log('abc');
}

btn.addEventListener('click', inClick);

To take it one step further you could add an id to the button

const body = document.body;
const textArea = document.createElement('textarea');
const button = document.createElement('button');
button.textContent = 'Click Me';
button.id = 'button-1' // add an id to it

body.append(textArea);
body.append(button)

// often referred to as a 'handler'
function clickHandler() {
  console.log('abc');
}

button.addEventListener('click', clickHandler);

// get newly created button from the DOM
console.log(document.getElementById('button-1'))
// <button id="button-1">Click Me</button>

I have implemented Archbald’s solution and it worked. Thank you for all the replies.

1 Like