开发者

Make a div a child of another div using Javascript

开发者 https://www.devze.com 2023-02-20 02:18 出处:网络
I\'ve created a div adiv how would I make开发者_Go百科 this div a child of bdiv using Javascript?Assuming adiv is created in Javascript and bdiv is created declaratively on the page:

I've created a div adiv how would I make开发者_Go百科 this div a child of bdiv using Javascript?


Assuming adiv is created in Javascript and bdiv is created declaratively on the page:

document.getElementById("bdiv").appendChild(adiv);


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>


assuming you've got your bdiv and adiv references to HTMLElements:

bdiv.appendChild(adiv);

adds adiv to bdiv as a last children.


see a complete example : http://jsfiddle.net/XFMUp/


You can use the appendChild function as follows:

<div id="diva">a</div>
<div id="divb">b</div>

The use the following javaScript to move the div having removed it.

var diva = document.getElementById("diva");
var divb = document.getElementById("divb");

diva.appendChild(divb);

Check out this example on jsFiddle

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号