user3191903
user3191903

Reputation: 245

Javascript addEventListener to the dynamic button

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 ?

Upvotes: 0

Views: 382

Answers (2)

Oscar Paz
Oscar Paz

Reputation: 18292

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.

Upvotes: 2

Russel Yang
Russel Yang

Reputation: 2701

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

Upvotes: 0

Related Questions