[英]How to dynamically create an element inside of a div?
Question is above, wondering how to dynamically create an element inside of a div.问题在上面,想知道如何在 div 内动态创建一个元素。 Right now I have figured out how to dynamically create an element, but it's not inside of any divs, using document.body.appendChild.
现在我已经想出了如何动态创建一个元素,但它不在任何 div 内,使用 document.body.appendChild。
Append it to the element where you want it to be inside of.将它附加到您希望它位于其中的元素上。
const parentElement = document.querySelector('.yourParentElement');
parentElement.appendChild(yourDynamicChildElement);
Another way I just found is to use to insertBefore, to insert it before something.我刚刚发现的另一种方法是使用insertBefore,将它插入到某些东西之前。 I put ap inside of my div where I wanted the element to go, and then it put the p inside of the div in the spot where I wanted my dynamically created element to go.
我将 ap 放在我希望元素所在的 div 中,然后将 div 中的 p 放在我希望动态创建的元素所在的位置。 Then, by using insertBefore, it would insert my dynamically created element right before the p, making it go where I wanted it to go.
然后,通过使用 insertBefore,它会在 p 之前插入我动态创建的元素,让它去我想要去的地方。
var element = document.createElement("yourElement");//make a var for the dynamically created element that you want to make
var parent = document.getElementById("divID");//ID of the <div>
var child = document.getElementById("pID");//ID of the <p> where I want my dynamically created element to go
<div>
<p id="pID"></p>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.