简体   繁体   English

如何在 Div 中动态添加段落?

[英]How can I add a Paragraph inside a Div dynamically?

I have this code which creates a div element:我有这段代码可以创建一个 div 元素:

 var div = document.createElement("div");
 var attr = document.createAttribute("id");
 attr.value="container";
 div.setAttributeNode(attr);
 document.body.appendChild(div);

How can I add the Paragraph tag inside of the Div element dynamically?如何在 Div 元素中动态添加 Paragraph 标签?

It should look like this:它应该是这样的:

<div id="container"
    <p class="album"><h2>1975</h2></p>
</div>

You could create another variable to house the element you're trying to create.您可以创建另一个变量来容纳您尝试创建的元素。 Consider this:考虑一下:

var div = document.createElement("div");
var attr = document.createAttribute("id");
var p = document.createElement("p"); //create the paragraph tag
p.classList += 'album'; // give it a class by adding to the list
p.innerHTML = '<h2>1975</h2>'; // add html text or make another element if needed.
attr.value="container";
div.setAttributeNode(attr);
div.appendChild(p); add the <p> element to the div 
document.body.appendChild(div);

You create the needed element with document.createElement() the set the needed attributes, classes, etc. Then once you have it setup you append the element variable to the parent element, like the div in this case.您可以使用document.createElement()创建所需的元素,并设置所需的属性、类等。然后一旦设置好,就将元素变量附加到父元素,例如本例中的 div。 You can follow this pattern to generate as much html as needed dynamically in JavaScript.您可以按照此模式在 JavaScript 中根据需要动态生成尽可能多的 html。

You can do the same with the <h2> element as well, like this:您也可以对<h2>元素执行相同操作,如下所示:

var h2Element = document.createElement('h2');
h2Element.innerText = '1975';
p.appendChild(h2Element);

The p variable houses the paragraph tag and the h2Element houses the content for that tag. p变量存放段落标签, h2Element存放该标签的内容。 However, I'd recommend that if you want an <h2> for the text it should be separate from the <p> as they are separate elements.但是,我建议如果您想要文本的<h2> ,它应该与<p>分开,因为它们是单独的元素。 For exmaple and h2 is a heading level two used before a paragraph, which is what a <p> is.例如,h2 是在段落之前使用的二级标题,这就是<p>含义。

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

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