简体   繁体   English

创建一个新元素 div 并将其包裹在现有元素周围 JavaScript

[英]Create a new element div and wrap it around an existing one with JavaScript

I am aware how to create a new div or any other HTML element and add it as a child using pure JavaScript.我知道如何创建一个新的 div 或任何其他 HTML 元素,并使用纯 JavaScript 将其添加为子元素。

Am I able to create a new element and add my existing one into it?我可以创建一个新元素并将现有元素添加到其中吗?

For example:例如:

I would like to take the current code below and put it within a brand new div.我想将下面的当前代码放在一个全新的 div 中。

// Current elements on page
<div>
  <img />
  <img />
</div>
<div>
  <p>Hello world</p>
</div>

What I want:我想要的是:

// What I want
<div class="my-new-div">
 <div>
  <img />
  <img />
 </div>
 <div>
  <p>Hello world</p>
 </div>
</div>

I understand this is easy to do in HTML however.我知道这在 HTML 中很容易做到。 I have to use JavaScript in this scenario to alter a webpage.在这种情况下,我必须使用 JavaScript 来更改网页。 In this scenario I must add a parent div to avoid changing styles.在这种情况下,我必须添加一个父 div 以避免更改 styles。

You can simply fetch the existing node, create a new one, insert it before the existing node, and finally append the existing node to the new node as child.您可以简单地获取现有节点,创建一个新节点,将其插入现有节点之前,最后 append 将现有节点作为子节点添加到新节点。 The browser moves the node when performing the "append" operation, if it is already contained somewhere in the document.如果节点已经包含在文档中的某处,则浏览器会在执行“追加”操作时移动该节点。

 const myDiv = document.getElementById("myDiv"); const myNewDiv = document.createElement("div"); myNewDiv.style.border = "solid 1px"; document.body.insertBefore(myNewDiv, myDiv); myNewDiv.appendChild(myDiv);
 <div id="myDiv"> <p>Hello</p> <p>Paragraph</p> </div>

To move one element from one part of the document to another part, you need to associate the element to a new parent.要将一个元素从文档的一部分移动到另一部分,您需要将该元素关联到新的父元素。 this automatically disassociates the moving element from its old parent.这会自动解除移动元素与其旧父元素的关联。

 function newAndMove() { //Create a new element let blue = document.createElement('DIV'); blue.classList.add('blue-div'); document.body.appendChild(blue); //Move existing element inside it let red = document.getElementById('old-div'); blue.appendChild(red); }
 .red-div { width: 200px; height: 200px; background-color: red; }.blue-div { width: 400px; height: 400px; background-color: blue; position: absolute; top: 100px; left: 100pxl }
 <input type="button" value="Get red inside new blue" onClick="newAndMove()"> <div class="red-div" id="old-div"></div>

you can move DOM elements by appending them as a child to the preferred container.您可以通过将 DOM 元素作为子元素附加到首选容器来移动它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM