javascript Uncaught TypeError: Cannot read propert

2019-06-16 12:28发布

问题:

This question already has an answer here:

  • Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null 25 answers

I am getting the following error in Google Chrome on a very old Form I inherited (seems to work OK in IE, no errors)

Uncaught TypeError: Cannot read property 'firstChild' of null

The error applies to the following js elem.firstChild.nodeValue = dispmessage;:

function msg(fld,     
         msgtype, 
         message) {
  if (emptyString.test(message))
    dispmessage = String.fromCharCode(nbsp);
  else
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;

  elem.className = msgtype;   // set the CSS class to adjust appearance of message
};

Wondering if someone has come across similar issue before? Any ideas on how I can resolve?

Cheers

回答1:

This error means the elem object is null. Check the fld value passed and see whether an object with that id actually exists in your code or not.