rony jacob
rony jacob

Reputation: 121

Getting null value on the querySelector

I try to copy paste the code from Mozilla's getting started with Javascript tutorial

var myImage = document.querySelector('img');

myImage.onclick = function() {
    var mySrc = myImage.getAttribute('src');
    if(mySrc === 'images/firefox-icon.png') {
      myImage.setAttribute ('src','images/firefox2.png');
    } else {
      myImage.setAttribute ('src','images/firefox-icon.png');
    }
}

I am getting an error "Cannot set property 'onclick' of null". How can correct the code?

I am just getting started with javascript. please forgive me if it is a silly mistake from my part.

Upvotes: 2

Views: 385

Answers (1)

Carlos Sultana
Carlos Sultana

Reputation: 709

You might be trying to assign the click handler before the element has been rendered so the query selector will not find the img tag. Try executing your script after the page has rendered like so

window.onload = function () {
    var myImage = document.querySelector('img');

    myImage.onclick = function() {
        var mySrc = myImage.getAttribute('src');
        if(mySrc === 'images/firefox-icon.png') {
          myImage.setAttribute ('src','images/firefox2.png');
        } else {
          myImage.setAttribute ('src','images/firefox-icon.png');
        }
    }
}

Upvotes: 1

Related Questions