Search code examples
javascriptphpif-statementnulltypeof

Cannot read style properties of null (even though the line of code is inside of an "if" asking is the variable is defined


In my website, there is a particular tab that only loades for specific users.

<?php if($User["UID"] == $SpaceCreatorUID){ echo "";?> <button class="button-container" id="qr-button">Mi QR<div id="qr-indicator" class="indicator"></div> </button> <?php echo ""; } ?>

Nothing special; works perfectly. However, when the tab does not load for a user (which is perfect), my JS code stops working at the following line (83):

qrIndicator.style.display = "none";

Makes total sense, since I would be trying to define the style property for a null object. Thus, I made the following change (line 83):

if (typeof qrIndicator !== 'undefined'){qrIndicator.style.display = "none";};

However, it keeps throwing the same error: Cannot read properties of null (reading 'style'). What is it that I'm missing or not understanding?

I'm leaving the following line (14) for context:

try{var qrIndicator = document.getElementById("qr-indicator");}finally{};

What could be causing this problem?


Solution

  • There’s no need for a try/catch, that won’t throw, it’ll instead return null which is easy to test for.

    var qrIndicator = document.getElementById("qr-indicator");
    
    if (qrIndicator){
      qrIndicator.style.display = "none";
    }