如何使用 class 添加子元素?通过JS

How to add child element with class ? through JS

我有一个具有以下 id 的元素="loader-wrap"

<div id="loader-wrap"></div>

我想添加一个新的 div 元素 btw 上面的父 div 自动包括添加 class "Pin" 我有这个 Id 元素的地方。

想要这个:<div id="loader-wrap"><div class="Pin"></div></div>

使用document.createElement()方法:

var pin = document.createElement("div"); // create new div
pin.setAttribute("class", "Pin"); // set class to the div

var loaderWrap = document.getElementById("loader-wrap"); // get the parent element
loaderWrap.appendChild(pin); // append the new div to the parent