Why is a DOM element null? [duplicate]

会有一股神秘感。 提交于 2020-01-03 17:34:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!