0

The following code throws an error message in the console and i don't understand this logic, because in my code you can see i have written if statements which should first check if the objects exist.

if (typeof document.getElementById("trbrok0").checked != "undefined") document.getElementById("trbrok0").checked = false;
if (typeof document.getElementById("trbrok1").checked != "undefined") document.getElementById("trbrok1").checked = false;
if (typeof document.getElementById("trbrok2").checked != "undefined") document.getElementById("trbrok2").checked = false;
if (typeof document.getElementById("trbrok3").checked != "undefined") document.getElementById("trbrok3").checked = false;

Like you can see we should first check if the object exists and then try to change the value of "checked" property in the object. But I always get the following error message:

Uncaught TypeError: Cannot read property 'checked' of null
2
  • 1
    the elements you try to access do not exist Commented Mar 2, 2018 at 10:48
  • You are trying to get checked property from null Commented Mar 2, 2018 at 10:49

3 Answers 3

5

Because document.getElementById("trbrok0") returns a DOM node and if it doesn't exist it returns null. null doesn't have a property checked so document.getElementById("trbrok0").checked throws the error.

The fix would be to add a check if the node exists first with if(document.getElementById("trbrok0")!= null){ }

Sign up to request clarification or add additional context in comments.

1 Comment

ok great so anyway there is a logic to check this good to know
1

Have a look

function checkNullAndSetVal(id, val) {
  if (document.getElementById(id) == null) {
    console.log(id + ", Null or Undefined");
    return;
  }

  document.getElementById(id)["checked"] = val;
  console.log("Successfully Updated: ", id);
}

checkNullAndSetVal("trbrok0", false);
checkNullAndSetVal("trbrok1", true);
checkNullAndSetVal("trbrok2", false);
checkNullAndSetVal("trbrok3", true);
<input id="trbrok2" type="checkbox" name="trbrok" value="2">
<input id="trbrok3" type="checkbox" name="trbrok" value="3">

Explanation:

  1. if you check for null with double equals to (==), then it check for both null & undefined
  2. Use a function to reduce repetition of code.
  3. Use square bracket syntax to create non existing properties in an object. e.g obj["newProperty"] = "Some Value";

Comments

0

When you check the type of the checked, the element, selected by document.getElementById doesn't exist, and that's why:

Cannot read property 'checked' of null

because null doesn't have a property named checked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.