最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot set property 'innerHTML' of null in Jquery - Stack Overflow

programmeradmin1浏览0评论

Getting Uncaught TypeError: Cannot set property 'innerHTML' of null. How to fix it.

$(window).load(function() {
   document.getElementById("id_city").innerHTML = ('<option>Select a City</option>');
   var selected_state = $('#id_state').val();
   var selected_city = $('#selected_city').val();
   var data = 'state='+selected_state  + '&selected_city='+selected_city; 
   var url = $('#url').val();
   $.ajax({
     type:"POST",
     url:url,
     data:data,    // multiple data sent using ajax
     success: function (response) {
     document.getElementById("id_city").innerHTML=response;
    } 
  });  
});

Getting Uncaught TypeError: Cannot set property 'innerHTML' of null. How to fix it.

$(window).load(function() {
   document.getElementById("id_city").innerHTML = ('<option>Select a City</option>');
   var selected_state = $('#id_state').val();
   var selected_city = $('#selected_city').val();
   var data = 'state='+selected_state  + '&selected_city='+selected_city; 
   var url = $('#url').val();
   $.ajax({
     type:"POST",
     url:url,
     data:data,    // multiple data sent using ajax
     success: function (response) {
     document.getElementById("id_city").innerHTML=response;
    } 
  });  
});
Share Improve this question asked Jan 12, 2017 at 12:47 Rupinder KaurRupinder Kaur 3176 silver badges22 bronze badges 1
  • be insure id_city is correct and element rendered on page – Sanjay Nishad Commented Jan 12, 2017 at 12:49
Add a ment  | 

5 Answers 5

Reset to default 3

This error means in this line:

document.getElementById("id_city").innerHTML

you have

document.getElementById("id_city") = null

Please make sure you have any markup with id parameters set to "id_city"

Make sure you are having an element with that id on the page. If possible please share the HTML for better result.

Example: <select id="id_city"></select>

The error line is document.getElementById("id_city").innerHTML and the reason could be

  • the element not in html
  • the script is called before the element is bound to html

try placing the script at the bottom of the page

you can use jquery method

$("#id_city").html(response);
document.getElementById("id_city").innerHTML=response;

to

document.getElementById("id_city").html(response);

or

$('#id_city').html(response);
发布评论

评论列表(0)

  1. 暂无评论