Getelementbyid Returns Null

getElementById returns null?

It can be caused by:

  1. Invalid HTML syntax (some tag is not closed or similar error)
  2. Duplicate IDs - there are two HTML DOM elements with the same ID
  3. 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



Leave a reply



Submit