
本文介绍了如何使用 JavaScript 在页面加载后动态创建和设置嵌套的 `div` 元素,包括创建 `p` 标签和 `iframe` 标签,并设置它们的属性和样式,以及使用 `innerHTML` 的方法。同时讨论了动态创建元素并编辑其属性的通用方法。
在前端开发中,有时需要在页面加载后动态地创建和添加 HTML 元素。 本教程将演示如何使用 JavaScript 实现这一目标,特别是针对嵌套 div 结构,并包含创建 p 标签和 iframe 标签的示例。
动态创建元素并添加到DOM
以下代码展示了如何使用 JavaScript 动态创建 <p> 和 <iframe> 元素,并将其添加到具有类名 newSyndicationModalContent 的 div 元素中。
const newSyndicationModalContainer = document.querySelector(".newSyndicationModalContainer");
const newSyndicationModalContent = document.querySelector(".newSyndicationModalContent");
if (newSyndicationModalContainer != undefined) {
var p = document.createElement('p');
p.innerText = "Hello!";
var iframe = document.createElement('iframe');
iframe.id = "syndicationPanelModalIFrame";
iframe.src = "http://sample.com";
iframe.width = "100%";
iframe.height = "100%";
iframe.style.border = "none";
newSyndicationModalContent.append(p, iframe);
newSyndicationModalContainer.style.display = 'block';
}这段代码首先获取了类名为 newSyndicationModalContainer 和 newSyndicationModalContent 的元素。 然后,它创建了一个 <p> 元素和一个 <iframe> 元素,并设置了 <iframe> 的属性,例如 id、src、width、height 和 style。 最后,它将 <p> 和 <iframe> 元素添加到 newSyndicationModalContent 元素中,并将 newSyndicationModalContainer 元素的 display 属性设置为 block,使其可见。
立即学习“Java免费学习笔记(深入)”;
相应的 HTML 结构如下:
<div class="newSyndicationModalContainer"> <div class="newSyndicationModalContent"> </div> </div>
以及对应的 CSS 样式:
.newSyndicationModalContainer {
display: none;
position: fixed;
z-index: 9999;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
.newSyndicationModalContent {
background-color: transparent;
margin: auto;
width: 100%;
height: 100%;
}使用 innerHTML 动态创建元素(不推荐)
虽然不推荐,但可以使用 innerHTML 属性来动态创建元素。 以下是一个示例:
const newSyndicationModalContainer = document.querySelector(".newSyndicationModalContainer");
const newSyndicationModalContent = document.querySelector(".newSyndicationModalContent");
if (newSyndicationModalContainer != undefined) {
newSyndicationModalContent.innerHTML = `<p>Hello</p><iframe src="https://sample.com" id="syndicationPanelModalIFrame" width="100%" height="100%" style="border: none;"></iframe>`;
newSyndicationModalContainer.style.display = 'block';
}这段代码直接将 HTML 字符串赋值给 newSyndicationModalContent 元素的 innerHTML 属性。 这种方法简单快捷,但存在安全风险(XSS 攻击)和性能问题,因此不建议在生产环境中使用。 建议优先使用 document.createElement 等方法来创建元素。
动态编辑元素的属性
可以动态地创建元素并编辑其属性,例如 innerHTML、outerHTML、innerText 等。
以下是一个示例:
let div = document.createElement("div");
div.innerHTML = `<span class="innerSpan" style="border: 5px ridge red" data-blablablah="I-don't-say-bla-bla-blah">Bla Bla Bla Blah</span>`;
div.style = "dispaly: grid";这段代码创建了一个 div 元素,并使用 innerHTML 属性设置其内容为一个包含样式的 span 元素。 然后,它使用 style 属性设置 div 元素的样式。
总结
本教程介绍了如何使用 JavaScript 动态创建和设置嵌套的 div 元素,包括创建 p 标签和 iframe 标签,并设置它们的属性和样式。 建议优先使用 document.createElement 等方法来创建元素,以提高代码的可维护性和安全性。 避免直接使用 innerHTML 赋值,除非在完全可信的环境下。










