简体   繁体   中英

Cannot set property 'innerHTML' of null Error

i have made a very basic and simple code in which i have an input field which is validated on every keypress but when i enter anything in the form nothing happens , when i tried the chrome developers this was the error "Cannot set property 'innerHTML' of null Error"

i don't get what am i doing wrong ,i know "document.getElementbyId('show')" returns null but why? someone help please! thank u

this is my index.html file

<script type="text/javascript">
var xmlHttp = new XMLHttpRequest();   

function validate(user){               
        xmlHttp.open("GET", "names.php?name="+user, true);             
        xmlHttp.onreadystatechange = function(){
            document.write("error");
            document.getElementById('show').innerHTML = xmlHttp.responseText;
        }
        xmlHttp.send(null);
}

<h2>Enter a name :</h2>
<form>
<input type="text" onkeypress="validate(this.value)" />
<div id="show"></div>
</form>

The problem is this line:

document.write("error");

When you use document.write() after the page has finished loading it kills the current page, so then there is no 'show' element to be found by document.getElementById('show') on the next line.

It looks to me like you just don't need the document.write() at all, because it doesn't really make sense to spit out a hardcoded "error" when you're trying to display xmlHttp.responseText in a div. If you do need to display an error just display it in that or another div the same way as with the response text.

页面加载后不要使用document.write ,因为它将替换页面的内容

It's because you're using document.write which is overwriting the whole page and hence 'deleting' div#show .

see: Why is document.write considered a "bad practice"?

Edit: Other answers are correct - document.write is replacing the content so the element no longer exists. The remainder of this answer is still valid though!

Presumably you only want to insert the HTML when the request has completed; to do this, filter based on the value of xmlHttp.readyState ;

xmlHttp.onreadystatechange = function(){
    if (xmlHttp.readyState !== 4) { return; }
    document.getElementById('show').innerHTML = xmlHttp.responseText;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM