JavaScript Uncaught TypeError: Cannot read property 'value' of null

用JavaScript操作DOM时出现如下错误:

   Uncaught TypeError: Cannot set property 'value' of null
   Uncaught TypeError: Cannot read property 'id' of undefined

例如:


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
    var div = document.getElementById("测试1");
    alert(div.id);
    alert(div.className);
    alert(div.title);
script>
<title>测试title>
head>
<body>
    <div id="测试1" class="测试2" title="测试3">
        <span>0span>
        <span>1span>
        <span>2span>
        <span>3span>
    div>
body>
html>

运行时出现如下错误:

JavaScript Uncaught TypeError: Cannot read property 'value' of null_第1张图片

问题出在JS运行的时候你的页面还没有加载完成,所以你的JS代码找不到你的页面元素,就会抛出这个问题。解决办法就是把JavaScript代码放在body的最后,例如:


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>测试title>
head>
<body>
    <div id="测试1" class="测试2" title="测试3">
        <span>0span>
        <span>1span>
        <span>2span>
        <span>3span>
    div>
<script>
    var div = document.getElementById("测试1");
    alert(div.id);
    alert(div.className);
    alert(div.title);
script>
body>
html>

JavaScript Uncaught TypeError: Cannot read property 'value' of null_第2张图片

你可能感兴趣的:(JavaScript,Questions,从菜鸟到大神问题锦集)