使用 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

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

Make a div a child of another div using Javascript

javascript

提问by Skizit

I've created a div adivhow would I make this div a child of bdivusing Javascript?

我已经创建了一个 divadiv如何让这个 div 成为bdiv使用 Javascript的子级?

回答by Town

Assuming adivis created in Javascript and bdivis 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 bdivand adivreferences to HTMLElements:

假设你有你的bdiv,并adiv引用到HTML元素:

bdiv.appendChild(adiv);

adds adivto bdivas a last children.

添加adivbdiv作为最后一个孩子。

回答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 上查看此示例