0

Hi In my code I'll add some dynamic buttons. Before adding that I am adding an event listener as follows

document.querySelector("input[name='btn']").addEventListener("click", runFunction);

But I am getting "Cannot call method addEventListener of null' in chrome console. How can I add event listner to the element that is not exists yet in plain Javascript ?

user3191903
  • 237
  • 2
  • 6
  • 14

2 Answers2

2

You can't add a listener to an element that does not exist yet. Either execute your script at the end of the page (before body close tag) or this way:

window.onload = function() {
    document.querySelector("input[name='btn']").addEventListener("click", runFunction);
};

document.querySelector() returns null if it doesn't find an element that matches the selector, and you can't invoke a method of a null object.

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42
0

Try to do it in document ready. if you use jQuery you can do something like this

$( function() {

document.querySelector("input[name='btn']").addEventListener("click", runFunction);

});

or

$(document).ready(function() { /* code here */ });

if you do not use jquery, you can use window.onload or window.document.onload

Russel Yang
  • 2,633
  • 3
  • 21
  • 18