getElementById returns null?
It can be caused by:
- Invalid HTML syntax (some tag is not closed or similar error)
- Duplicate IDs - there are two HTML DOM elements with the same ID
- Maybe element you are trying to get by ID is created dynamically (loaded by ajax or created by script)?
Please, post your code.
getElementById() returns null even though the element exists
You have to put this in a document
load
event. The DOM hasn't gotten to abc
by the time the script is executed.
Keep getting an error because getElementById returns null
Your script is running before the body
is encountered so at that point, the element doesn't exist and your document.getElementById("sjuku")
line fails. Move your script to just before the closing body
tag.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="sjuku"></div>
<script src="main.js"></script>
</body>
</html>
document.getElementById(); returns null on an id that definitely exists
This is because your script is running before the DOM is fully loaded. You can either place the script at the bottom of the body or wrap your code with DOMContentLoaded. This will ensure that code placed inside will only be executed once the DOM is fully loaded.
<!DOCTYPE html><html><head> <link rel="stylesheet" type="text/css" href="home.css" /> <script> document.addEventListener("DOMContentLoaded", function(event) { console.log(document.getElementById("closebtn")); }); </script></head><body> <div id="menubar"> <button id="closebtn" onclick=""></button> </div></body></html>
document.getElementById returns null in Chrome Console
The element with that ID does not belong to the document
. It belongs to the shadow DOM attached to the <game-theme-manager>
element.
Related Topics
Canvas.Todataurl() Securityerror
Format Date to Mm/Dd/Yyyy in JavaScript
Remove Items from Array with Splice in for Loop
How to Convert Blob to File in JavaScript
How to Set Time Delay in JavaScript
JavaScript - Cannot Set Property of Undefined
Is the Promise Constructor Callback Executed Asynchronously
How to Guarantee That My Enums Definition Doesn't Change in JavaScript
What Is "Export Default" in JavaScript
Jquery Checkbox Checked State Changed Event
Jquery to Loop Through Elements with the Same Class