Home > Software engineering >  Uncaught TypeError: id name is null, whilst error checking should prevent this error
Uncaught TypeError: id name is null, whilst error checking should prevent this error

Time:09-09

I have a javascript module which is listens to an addEventListener, and when the event takes places, an image is being removed from the html. After removal of the image, when the element of interest is clicked again the following error is prompted:

Uncaught TypeError: ID_2 is null
<anonymous> remove.js:9
EventHandlerNonNull* remove.js:3
EventListener.handleEvent* remove.js:2

Because of this, I added a check to see if the variable is present, but when I click the element for a 6th time, the error pops up again and from the debugging terminal it is shown that ID2 from ID_2.remove(); is causing the error. How can this error still be prompted with the 6th click? When my javascript first of all does not meet the condition count === 5, and second of all with ID_2 being null?

var count = 0;

document.addEventListener('DOMContentLoaded', function(){
    document.querySelector("#ID_1").onclick = function(){
        if(count === 5){

        var ID_2 = document.querySelector("#ID_2");
        if(ID_2 !== 'null' ){ID_2.remove();}
        }

        else{count  ;}
        }})

CodePudding user response:

the problem arises because you are checking if ID_2 is not equal to the string "null". This is wrong because you want to check if it is null.

The correct way would be:

    var ID_2 = document.querySelector("#ID_2");
    if(ID_2 !== null ){
      ID_2.remove()
    }

Alternatively, you can check for both null and undefined by simply checking if ID_2 has a valid value:

    var ID_2 = document.querySelector("#ID_2");
    if(ID_2){
      ID_2.remove()
    }

The second alternative is the same as:

var ID_2 = document.querySelector("#ID_2");
if(ID_2 !== undefined || ID_2 !== null){
  ID_2.remove()
}

Hope this answered your question!

  • Related