【发布时间】:2018-08-19 21:05:49
【问题描述】:
我正在学习 javascript 并在 DOM 中添加/删除元素,但我对看起来应该很简单的事情感到困惑。我想在正文中的所有元素周围创建一个带有 ID 的新 div 包装器。如果可能的话,我更喜欢使用 Vanilla Javascript 而不是 jQuery。
HTML:
<h1>Javascript Testing Header</h1>
<p>This is some text inside of my javascript testing page.</p>
<p>This is another simple paragraph.</p>
<h2>I like foods like:</h2>
<ul>
<li>Apples</li>
<li>Chocolate</li>
<li>Thin Mints</li>
<li>Tiger Trees</li>
<li>Feet Mangroves</li>
</ul>
Javascript:
// puts all the elements in <body> into it's own variable
var header1 = document.querySelector('h1');
var para = document.querySelectorAll('p');
var header2 = document.querySelector('h2');
var list = document.querySelector('ul');
// creates the new dynamic div
var newDivWrapper = document.createElement('div');
// gives newly created dynamic div id=container
newDivWrapper.id = 'container';
var bodyTag = document.querySelector('body');
// appends the newDivWrapper to the end of the DOM, just above </body>
var newDivWrapper = bodyTag.appendChild(newDivWrapper);
function replaceContent() {
document.newDivWrapper.innerHTML = header1 + para + header2 + list;
}
replaceContent();
上面的不行,它会创建新的 div 并将其添加到 DOM 的末尾。但是,我不确定是否应该在将 DOM 中的旧元素保存到 var 后删除它们,或者它们的位置是否可以移动。另外,我很确定我不能使用 innerHTML 将文本以外的任何内容写入元素。
【问题讨论】:
标签: javascript html dom dynamic