What is wrong with this JavaScript code please!! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is wrong with this JavaScript code please!!

Im trying to add an event listener to a button in order to carry out a certain function but it has an error. It says that it cannot read properties of null,i dont understand. var btn=document.getElementById("button"); btn.addEventListener('click',add); Function add(){ alert("worked"); }

27th Mar 2023, 4:44 PM
Michael Kamau
Michael Kamau - avatar
4 Answers
+ 3
This post might help you understand why https://www.sololearn.com/post/90825/?ref=app
27th Mar 2023, 5:53 PM
Ipang
+ 6
Please link your complete code. We can only add the event, once the html element is found – we need to "wait" for the DOM to be loaded. There is a typo btw: "function", not "Function"
27th Mar 2023, 5:07 PM
Lisa
Lisa - avatar
+ 3
Michael Kamau please share complete code
27th Mar 2023, 5:28 PM
Sakshi
Sakshi - avatar
+ 1
Thank you Ipang,the post you shared has helped me understand something
27th Mar 2023, 6:17 PM
Michael Kamau
Michael Kamau - avatar