Wrote a function and got an error when calling.”Uncaught TypeError: Cannot set property ‘innerHTML’ of null”
Code Below
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
var func3 = function(a,b){
return a + b
}
console.log(func3(1,2))
var x = func3(99, 1)
console.log(x)
document.getElementById('demo').innerHTML = x;
</script>
</head>
<body>
<p id=demo>The value to be modified</p>
</body>
</html>
explains: the reason for the error is that the innerHTML in document is empty, that is to say, when loading the JS file, the object called is the < in the text. p> Label
Therefore, you need to place the JS file reference in <p> After the label, i.e
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
var func3 = function(a,b){
return a + b
}
console.log(func3(1,2))
</script>
</head>
<body>
<p id=demo>The value to be modified</p>
<script>
var x = func3(99, 1)
document.getElementById('demo').innerHTML = x;
</script>
</body>
</html>
Conclusion: this small problem exposes the problem of understanding the loading order of HTML files. That is, the content in html is loaded in the order of HTML itself
Therefore, when introducing JS or adding <script> Content is executed after HTML content
Similar Posts:
- How to Solve Error: Cannot set property ‘onclick’ of null
- [How to Solve] Cannot set property ‘onclick’ of null
- Document.body.clientheight cannot get the browser page height correctly
- Always report uncaught error:[$ injector:modulerr ]Solutions to errors
- How to Add a Upload Files Function with Cypress
- Syntax error reported by JavaScript function: expected expression, got ‘;’
- Error in JS function referencing public page [How to Solve]
- document.body.scrollTop or document.documentElement.scrollTop
- [Solved] typescript:error TS2531: Object is possibly ‘null’.
- ”Cannot read property ‘addEventListener’ of null“