使用 Javascript 将 div 设为另一个 div 的子级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5460003/
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
Make a div a child of another div using Javascript
提问by Skizit
I've created a div adiv
how would I make this div a child of bdiv
using Javascript?
我已经创建了一个 divadiv
如何让这个 div 成为bdiv
使用 Javascript的子级?
回答by Town
Assuming adiv
is created in Javascript and bdiv
is created declaratively on the page:
假设adiv
是在 Javascript 中创建的,并bdiv
在页面上以声明方式创建:
document.getElementById("bdiv").appendChild(adiv);
回答by Lalchand
Here is the sample code
这是示例代码
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function appendDiv()
{
var div1=document.getElementById('div1');//get the div element
var div2=document.createElement("div");//create a new div
div2.innerHTML="div2";
div1.appendChild(div2);// append to div
}
</script>
</head>
<body onload=appendDiv()>
<div id="div1">
div1
</div>
</body>
</html>
回答by wildcard
assuming you've got your bdiv
and adiv
references to HTMLElements:
假设你有你的bdiv
,并adiv
引用到HTML元素:
bdiv.appendChild(adiv);
adds adiv
to bdiv
as a last children.
添加adiv
到bdiv
作为最后一个孩子。
回答by Alex Pacurar
see a complete example : http://jsfiddle.net/XFMUp/
查看完整示例:http: //jsfiddle.net/XFMUp/
回答by Swaff
You can use the appendChildfunction as follows:
您可以按如下方式使用appendChild函数:
<div id="diva">a</div>
<div id="divb">b</div>
The use the following javaScript to move the div having removed it.
使用以下 javaScript 移动已删除它的 div。
var diva = document.getElementById("diva");
var divb = document.getElementById("divb");
diva.appendChild(divb);
Check out this exampleon jsFiddle
在 jsFiddle 上查看此示例