0

When I run the code below, Safari's debug console tells me:

TypeError: Result of expression 'document.getElementById("txtHint")' [null] is not an object.

It seems to be throwing the error at this line:

document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

Code

 function showItem(str)
{
if (str.length==0)
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200 && xmlhttp.responseText!='')
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getitem.php?q="+str,true);
xmlhttp.send();
}

I am unsure of why this eror is thrown. There is absolutely a DIV with an ID of "txtHint" and yet safari cannot seem to run this code correctly. I guess my question is, what is wrong with this block of code.

2
  • 4
    What's the question here? Sounds like there's no element with that ID. Commented Nov 13, 2010 at 5:58
  • What does console.log(document.getElementById('txtHint').length); say? Commented Nov 13, 2010 at 6:08

3 Answers 3

1

Is this not a duplicate question? Anyway, try throwing the script before the end body tag or invoking the function after dom ready / window load.

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

3 Comments

Right, window.onload or a DOM ready function. I would personally convert your code to jQuery.
I saw that in the last answer you gave me however I am so new to this I was a little overwhelmed. What are the advantages of going to jquery with this code?
jQuery abstracts away browsers differences, so you don't need to do things like: if (window.XMLHttpRequest) { // code for new browsers
1

It's not a syntax issue, it tells you that document.getElementById("txtHint") returned null (i.e. there was no element with that id), which means the result (null) is not an object, which means you can't call .innerHTML on it.

Comments

0

Yes, agree with Ian Henry. From the error message, I guess that there is no element whose id is "txtHint" in the document .

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.