首页 > 解决方案 > 使用 createElement 将新段落添加到现有段落并保持相同的 css

问题描述

我正在使用 javascript 在 html 代码页的现有段落下方添加一个新段落。新段落没有遵循与第一个相同的 css。这是源代码的链接http://students.cpcc.edu/~lplumme2/web115/swtl/seventh10chaptersexamples.html

function seventh10() {
    alert("let's start the javascipt");
    var para = document.createElement("p");
    var t = document.createTextNode("We have different ways of teaching you. Our office location is designed to look like a student lab.We can work with you one on one there or you can meet you somewhere else or we can even come to your house");
    para.appendChild(t);

    document.getElementById("myBlog").appendChild(para);
}

seventh10();
<p id="myBlog">
    We have a variety of subjects and software that we can help you<br>
    improve your skills on. We teach from brand new levels to just helping<br>
    build on what you already know.<br>
</p>

标签: javascripthtmlcss

解决方案


您的代码<p> 现有的<p>. 这意味着左边距 CSS 规则适用于第二个与同样具有较大左边距的容器<p>相关的规则。

为防止这种情况,您可以将新<p>元素添加到包含现有<p>.

无论如何,将 a 添加<p>为另一个的孩子<p>有点不自然。浏览器将允许您以任何您喜欢的方式操作 DOM,但 HTML 解析器不会这样做。A<p>不能包含 HTML 规则下的块内容。


推荐阅读