Javascript 在javascript中的div元素内创建一个div元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12622465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a div element inside a div element in javascript
提问by Komal Waseem
I'm trying a very basic example of creating a div
inside an already existing div
.
我正在尝试一个非常基本的例子,div
在一个已经存在的div
.
It doesn't seem to be working when I use:
当我使用时,它似乎不起作用:
document.getElementbyId('lc').appendChild(element)
but works fine when I do this:
但是当我这样做时效果很好:
document.body.appendChild(element)
Do I need to add windows.onload
function? Though it doesn't work even then!
我需要添加windows.onload
功能吗?虽然即使那样也行不通!
HTML code:
HTML代码:
<body>
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />
<div id="lc">
</div>
</body>
JS code:
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);
}
回答by Develoger
Your code works well you just mistyped this line of code:
您的代码运行良好,您只是打错了这行代码:
document.getElementbyId('lc').appendChild(element);
document.getElementbyId('lc').appendChild(element);
change it with this: (The "B" should be capitalized.)
用这个改变它:(“ B”应该大写。)
document.getElementById('lc').appendChild(element);
HERE IS MY EXAMPLE:
这是我的例子:
<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>
回答by Anoop
'b' should be in capital letter in document.getElementById
modified code jsfiddle
'b' 应该在document.getElementById
修改后的代码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);
}
回答by Alexander Pavlov
Yes, you either need to do this onload
or in a <script>
tag afterthe closing </body>
tag, when the lc
element is already found in the document's DOM tree.
是的,你要么需要做这个onload
或在<script>
标签后关闭</body>
标签,当lc
元素在文档的DOM树已经被发现。