如何让 div 元素包裹其他元素?(伪选择器出现在代码中)

How to make a div element wrap other elements?(preudo selectors are present in code)

这是我试图达到的结构:

<div class="images">
  <div class="image">
   <div class="box">
      ::before
      <a><img></a>
   </div>
  </div>
</div>

但我得到:

<div class="images">
  <div class="image">
   <div class="box">::before</div>
      <a><img></a>       
  </div>
</div>

我尝试了很多选项,但我无法使框 div 包裹 link 和 img。我该怎么做?

 var image = document.createElement("div");
     image.className = "image";
 var images = document.createElement("div");
     images.className = "images";

 var foto = document.createElement("img"); 
 var a = document.createElement('a');

 a.appendChild(foto);

 var box = document.createElement('div');
     box.className = 'box';
     box.append(a)

     image.append(box);
     image.append(a);
     images.append(image);

按照这个顺序做对我有用。

var images = document.createElement("div");
    images.className = "images";
var image = document.createElement("div");
    image.className = "image";
var box = document.createElement('div');
    box.className = 'box';
var foto = document.createElement("img"); 
var a = document.createElement('a');

a.appendChild(foto);
box.appendChild(a);
image.appendChild(box);
images.appendChild(image);

// this is to see it in dom:
document.body.appendChild(images);

您应该使用 appendChild 而不是 append,这样元素实际上是附加在 内部 而不是一个接一个。

此外,不需要 image.append(a),因为 a 将与 box:

一起附加到 image

//creating the elements
var image = document.createElement("div");
image.className = "image";

var images = document.createElement("div");
images.className = "images";

var foto = document.createElement("img"); 
var a = document.createElement('a');
var box = document.createElement('div');
box.className = 'box';

//appending elements inside each other
box.appendChild(a); //appendChild so that the <a> tag is *inside* the div
a.appendChild(foto);
image.appendChild(box);
images.appendChild(image);

//finally, appending everything to the body (for this example)
document.body.appendChild(images);

好了:

var image = document.createElement("div");
            image.className = "image";
var images = document.createElement("div");
            images.className = "images";

var box = document.createElement('div');
var foto = document.createElement("img"); 
var newlink = document.createElement('a');

newlink.append(foto);
box.append(newlink);

image.append(box);
images.append(image);



document.getElementsByTagName("body")[0].append(images);