2012-09-27 22 views
15

一個div元素內部的div元素,我想一個已經存在的div內創建div的一個非常基本的例子。創建在JavaScript

這似乎

並不奏效,當我使用:

document.getElementbyId('lc').appendChild(element) 

,但能正常工作當我這樣做:

document.body.appendChild(element) 

我是否需要添加windows.onload功能?雖然它不起作用!

HTML代碼:

<body> 
    <input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" /> 

    <div id="lc"> 
    </div> 
</body> 

JS代碼:

function test() 
{ 
    var element = document.createElement("div"); 
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat')); 
    document.getElementbyId('lc').appendChild(element); 
    //document.body.appendChild(element); 
} 
+0

您可能想試試螢火蟲 - 讓它更容易在您的代碼中發現拼寫錯誤。 –

回答

24

您的代碼工作得很好,你輸錯這行代碼:

document.getElementbyId('lc').appendChild(element); 

改變其與此:

document.getElementById('lc').appendChild(element); 

這裏是我的例子:

<html> 
<head> 

<script> 

function test() { 

    var element = document.createElement("div"); 
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat')); 
    document.getElementById('lc').appendChild(element); 

} 

</script> 

</head> 
<body> 
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" /> 

<div id="lc" style="background: blue; height: 150px; width: 150px; 
}" onclick="test();"> 
</div> 
</body> 

</html> 
+1

這顯然是一個錯誤的問題。他說他的代碼工作正常。 –

+0

我添加了一個工作示例,所以我想我回答了全部問題。 – Develoger

+1

他說,當他追加到身體,而不是到div –

0

是的,你要麼需要做到這一點onload或在<script>標籤後收盤</body>標籤,當lc元素已經在文檔的DOM樹中找到了。

4

「 b」應該是大寫字母在document.getElementById改性的共de jsfiddle

function test() 
{ 

var element = document.createElement("div"); 
element.appendChild(document.createTextNode('The man who mistook his wife for a hat')); 
document.getElementById('lc').appendChild(element); 
//document.body.appendChild(element); 
}