问题
I have this simple HTML file:
<!DOCTYPE html>
<html>
<head>
<script src='test.js'></script>
</head>
<body>
<p>I am a paragraph tag</p>
<h1 >I am an h1 tag</h1>
<div id="id"> I am a div tag</div>
</body>
And this simple script (test.js):
y=document.getElementById("id");
y.style.color="green";
Why on earth is "y" null? The error I'm getting is
TypeError: y is null
I'm sure this is a simple syntax thing that I'm missing, but I can't for the life of me figure it out! Help!
Post Script: Both the html file and the test.js file are in the same folder.
回答1:
you have to place the script at the end of the document when all the elements are created:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>I am a paragraph tag</p>
<h1 >I am an h1 tag</h1>
<div id="id"> I am a div tag</div>
</body>
<script src='test.js'></script>
回答2:
You can wrap the content on your script using $(document).ready if you are using jQuery or window.onload if using plain javascript.
来源:https://stackoverflow.com/questions/37846803/why-is-a-dom-element-null