L
L
lowsentmy2020-05-09 14:41:09
JavaScript
lowsentmy, 2020-05-09 14:41:09

Uncaught TypeError: Cannot read property 'innerHTML' of null. Where is the mistake?

<!DOCTYPE html>
<html lang="ru">
<head>
  <script src="script.js"></script>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h1 id="text_1">Привет, мир!</h1>
</body>
</html>


var text = document.getElementById("text_1")
alert(text.innerHTML)


The result of this code is Uncaught TypeError: Cannot read property 'innerHTML' of null even though I should be able to see the contents of the tag.
I tried to deal with the problem, I found out that such an error occurs when the id does not exist, but as you can see, everything converges. With this, this code works in JsFiddle

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-05-09
@lowsentmy

You connect your script before all the page elements are loaded and it turns out that the element you need on the page does not really exist at the time the script is executed.
You need to either add a "defer" attribute to the "script" tag, or put the "script" tag before the closing "body" tag

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question