【发布时间】:2018-04-04 22:35:05
【问题描述】:
由于某种原因,我的代码不起作用。当我尝试查看控制台将返回什么时,它会在返回时给我想要的答案:“未捕获的 TypeError:无法读取属性 'appendChild' of null”当我对 Div 进行同样的操作时。
这是我的代码,请帮助我...
function addOnePropertie () {
var theUl = document.createElement ("UL");
var theText = document.createTextNode ("This is a paragraph.");
theUl.appendChild (theText);
document.getElementById('theUlDiv').appendChild (TheUl);
}
<div class="divOne">
<header>
Sign Up an Object
</header>
<ul>
<span class="spanObject"> Name of Object: </span>
<input placeholder="Type any Name...">
</ul>
<hr class="inDiv">
<ul>
<span class="spanObject"> Name plus Value of Propertie One: </span>
<input class="smallInput" placeholder="Name of Propertie...">
<input class="smallInput" placeholder="Value of Propertie">
</ul>
<div id="theUlDiv">
</div>
<button class="addPropertie" onclick="addOnePropertie ();">
Add a Propertie
<i class="material-icons" style="color: blue; font-size: 15px;">
note_add
</i>
</button>
</div>
如您所见,如果我 console.log (theUl) 它返回了我想要的新 Ul 元素,如果我尝试将它放入 document.body.appendChild (theUl) 中也是如此,但如果我在 div 中这样做它不起作用,请帮助我出去了:D
【问题讨论】:
-
为什么要尝试将纯文本直接放到
<ul>? -
HTML 中的目标 div 有
theUlDiv类,但您尝试通过 id 找到它 -
是的,这是我的一个非常愚蠢的错误,看不到 class 而不是 id 但即便如此,它返回给我的却是完全相同的东西...... null 并且不起作用!
-
将你的函数定义更改为
window.addOnePropertie = function () {,然后用变量命名修复一些错误,然后它就可以工作了
标签: javascript html css append appendchild