简体   繁体   English

如何动态创建+插入(追加??)一个div到一个div容器中?

[英]How do I dynamically create + insert (append??) a div into a div container?

I would like it to end up as this:我希望它最终是这样的:

<div id = "container">

<div id = "dynamicallyCreated"></div>

</div> 

I'm pretty sure that this involves either document.createElement or appendChild, but I am not quite sure how to use these to insert the newly created div into the container div.我很确定这涉及 document.createElement 或 appendChild,但我不太确定如何使用它们将新创建的 div 插入到容器 div 中。

Edit: sorry, I'm not quite sure how to do the code snippet correctly编辑:抱歉,我不太确定如何正确执行代码片段

I'm pretty sure that this involves either document.createElement or appendChild我很确定这涉及 document.createElement 或 appendChild

Both, actually: :-)两者,实际上::-)

const div = document.createElement("div");
div.id = "dynamicallyCreated";
document.getElementById("container").appendChild(div);

More to explore on MDN : createElement , appendChild MDN 上有更多值得探索的内容: createElementappendChild

You can also use markup if you prefer via insertAdjacentHTML :如果您愿意,也可以通过insertAdjacentHTML使用标记:

document.getElementById("container").insertAdjacentHTML(
    "beforeend",
    "<div id='dynamicallyCreated'></div>"
);

It can add text in front of, after, at the beginning of, or at the end of an element.它可以在元素的前面、后面、开头或结尾添加文本。 (Or if adding text, insertAdjacentText .) (或者如果添加文本, insertAdjacentText 。)

If adding not at the end of the container, you can use insertBefore .如果不在容器末尾添加,可以使用insertBefore

This is how you can do it:你可以这样做:

  1. Create element using document.createElement()使用document.createElement()创建元素
  2. Add attributes (if you wish)添加属性(如果需要)
  3. Append it to the parent element, using appendChild() . Append 它到父元素,使用appendChild()

 var newEl = document.createElement('div'); newEl.setAttribute("id", "newElement"); document.querySelector("#container").appendChild(newEl);
 #container { width: 100px; height: 100px; background: red; } #newElement { width: 50px; height: 50px; background: yellow; }
 <div id="container"> </div>

Another approach for the same can be done using innerHTML property:可以使用innerHTML属性完成相同的另一种方法:

 document.querySelector('#container').innerHTML = "<div id='newElement'></div>"
 #container { width: 100px; height: 100px; background: red; } #newElement { width: 50px; height: 50px; background: yellow; }
 <div id="container"> </div>

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

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