Sushant
Sushant

Reputation: 21

New in programming and don't understand the error Uncaught TypeError: document.getElementById(...) is null

index.html

<head>
    <script src="app.js"></script>
    <!-- <script src="error.js"></script> -->
</head>
<body>
    <p id="element">GetElementById</p>
</body>
</html>

app.js

console.log("Start");


document.getElementById("element").innerHTML = "Solve";


console.log("Stop")

if you are new in JavaScript you will get error once you run this code. This just for those who are new in this field and learning online and nobody to helping.

Upvotes: 0

Views: 113

Answers (2)

Vaibhav
Vaibhav

Reputation: 57

This is happening because the element you are trying to access hasn't been created yet, inside the DOM. You are trying to change an element which doesn't exist.

Even though the id="element" has been defined in the html, but the script is executed first and only after that the DOM creation is given preference by javascript.

To avoid such cases, the best practice is to use '&&' or ternary operators.

I know those words might sound overwhelming to a newbie programmer, but essentially you're trying to check if that element exists or not, before making the change.

Just change your code to:

document.getElementById("element") && document.getElementById("element").innerHTML = "Solve";

or you can use ternary operators like this:

document.getElementById("element")?document.getElementById("element").innerHTML = "Solve":"";

Upvotes: 1

Sushant
Sushant

Reputation: 21

I am trying to help new programmer when I don't understand JavaScript error reason.

sometime you get error getElementById(...) is null. there could be many reason I am posting one solution that may solve your issue

When you are new in programing and run above code you will get an error which have simple solution.

Error : Uncaught TypeError: document.getElementById(...) is null

This is just because of script tag that you have placed top of file basically before html element that you try to get by Id.

<html lang="en">
<head>
</head>
<body>
    <p id="element">GetElementById</p>
    <script src="app.js"></script>
    <!-- Script below the element or you can place at the bottom  -->
    <h1>Javascrit</h1>
</body>
</html>

Upvotes: 2

Related Questions