-1

I'm trying to figure out why I get this error from some visitors via my JS error console tracker:

Uncaught TypeError: Cannot read property 'classList' of null

The code in question is:

                if (typeof item == "object") {
                    item.classList.remove('active');
                    update_specific_marker(item.getAttribute('data-what'),"remove_active_icon");
                }

Shouldn't this bit work:

if (typeof item == "object") {

I'm baffled as to how they get it in the first place - as I can't get any errors to come out from that page (no matter how much I play with it, even in Chrome which is where it seems to come from)

Any suggestions on what I could try?

Andrew Newby
  • 4,941
  • 6
  • 40
  • 81

2 Answers2

2

If you do typeof null in a JS console, it will print object. so in your case if item = null then also typeof item == "object" will produce true

what you can do instead is

if(item){
  // do things
}
Prithwee Das
  • 4,628
  • 2
  • 16
  • 28
1

For item = null, typeof item == "object" is true, so inside the block you're trying to access the classList property of a null value. You can't do that, hence the error.

To fix it, you're going to need another condition to stop null values from accessing the code.

if (typeof item == "object" && item != null)
Angel Politis
  • 10,955
  • 14
  • 48
  • 66