ElementById finds element but won't add event listener (Chrome extension)

你说的曾经没有我的故事 提交于 2019-12-24 21:05:55

问题


I have a form in my extension's popup with the code:

<button type="submit" id="update" class="btn btn-primary">Submit</button>

And then in the attached script, the following code:

document.addEventListener("DOMContentLoaded", function(event){
  var button = document.getElementById("update");
  button.addEventListener("click", test);
  button.style.color="red";
});



function test(){
  console.log("test");
}

The "button.style.color="red"" portion of the code works, so I know that the button was found successfully. However, I still receive this error upon load and when the button is clicked:

Uncaught TypeError: Cannot read property 'addEventListener' of null

How do I fix this :(


回答1:


It is working in my demos, see: JSBin

    document.addEventListener("DOMContentLoaded", function(event){
     var button = document.getElementById("update");
     button.addEventListener("click", test);
     button.style.color="red"; 
    });



回答2:


This could be a possible duplicate Cannot read property 'addEventListener' of null but, try these solutions out, if your still having trouble explain more in detail.



来源:https://stackoverflow.com/questions/53575767/elementbyid-finds-element-but-wont-add-event-listener-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!