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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:51:51  来源:igfitidea点击:

Creating a div element inside a div element in javascript

javascriptdomcreateelement

提问by Komal Waseem

I'm trying a very basic example of creating a divinside 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.onloadfunction? 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.getElementByIdmodified 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 onloador in a <script>tag afterthe closing </body>tag, when the lcelement is already found in the document's DOM tree.

是的,你要么需要做这个onload或在<script>标签关闭</body>标签,当lc元素在文档的DOM树已经被发现。