How To Solve Typeerror: Document.queryselector(...) Is Null?
I am trying to target the image using document.querySelector() but it is giving me an error saying TypeError: document.querySelector(...) is null Here is my code:
Solution 1:
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly common mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
Your script is running before the DOM is ready. You have to wrap your code with DOMContentLoaded
:
<!DOCTYPE html><html><head><metacharset="utf-8"><title>Step 1</title><style>
#image1{
}
</style><script>document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector('#image1').addEventListener("click",myFunction);
// addEventListener(event, function, useCapture)functionmyFunction(){
alert("alert on click");
}
});
</script></head><body><imgsrc="images/image1.jpg"id="image1" /></body></html>
Post a Comment for "How To Solve Typeerror: Document.queryselector(...) Is Null?"