开发者

JavaScript cannot identify element in HTML

开发者 https://www.devze.com 2023-01-25 09:38 出处:网络
My JavaScript code is supposed to receive data using AJAX and display it in a DIV called \"txtHint\". However, this is the error I get when the code executes (I am using the build-in debugger in Safar

My JavaScript code is supposed to receive data using AJAX and display it in a DIV called "txtHint". However, this is the error I get when the code executes (I am using the build-in debugger in Safari):

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

Here is the code:

function showItem(str)
{
if (str=="")
  {
  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开发者_如何学C==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getitem.php?q="+str,true);
xmlhttp.send();
}

Now i get: TypeError: Result of expression 'el' [undefined] is not an object.

Does this mean my element does not exist?


First, check if the element exists.

var el = document.getElementById('txtHint');
if ( el ) {  
   el.innerHTML = xmlhttp.responseText;
}

Make sure you are binding this after the element has been generated in the DOM. You can also wait for the entire window to load via window.onload = showItem.

People use frameworks like jQuery to save time. Your code would result in something as succinct as:

$(function() {
   function blah(str) {
      if ( str == '' ) {
        $('#txtHint').html('')
        return;
      }

      $.ajax({ url:'blah.php', success:function(html) {
        $('#txtHint').html(html);
      } })
   }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消