我有一个使用DOM / JS创建的div。我有另一个div,我有一些html,我想放在DOM div内。我;对JS来说还很陌生,因此不胜感激。
//The DOM div
div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "0px";
div.style.top = "0px";
div.style.width = "240px";
div.style.height = "auto";
div.style.background = "red";
div.style.padding = "15px 0px 0px 0px";
div.style.color = "white";
div.id = "chat";
<!--The existing div code-->
<div id="page-wrap">
<h2>Chat</h2>
<p id="name-area"></p>
<div id="chat-wrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
</form>
</div>
答案 0 :(得分:1)
您可以按照以下方式使用innerHTML
和outerHTML
属性:
const div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "0px";
div.style.top = "0px";
div.style.width = "240px";
div.style.height = "auto";
div.style.background = "red";
div.style.padding = "15px 0px 0px 0px";
div.style.color = "white";
div.id = "chat";
//
div.innerHTML += document.getElementById('page-wrap').outerHTML;
document.getElementById('page-wrap').remove(); // remove the previous one;
document.body.append(div);
<div id="page-wrap">
<h2>Chat</h2>
<p id="name-area"></p>
<div id="chat-wrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
</form>
</div>
答案 1 :(得分:0)
鉴于您已经创建了divElement,则只需使用id / class等在HTML中获取div ...例如:
var htmlDiv = document.getElementById('chat-area')
然后您只需将创建的div附加如下:
htmlDiv.append(myCreatedDiv)
答案 2 :(得分:0)
使用appendChild
方法将元素添加到另一个(纯JavaScript)
div = document.createElement("div");
div2 = document.createElement("div");
div.appendChild(div2);
替代方法是yahya提到的jQuery的append
,它在内部使用appendChild
方法。