如何操作DOM以使用Javascript嵌套元素?
我有一个测试项目,我使用Firebase作为在HTML页面上呈现数据的一种方式。它工作得很好,但我需要在类中包含更多嵌套的HTML div来维护我的布局。有可能这样做吗?我有以下Javascript如何操作DOM以使用Javascript嵌套元素?,javascript,firebase,dom,Javascript,Firebase,Dom,我有一个测试项目,我使用Firebase作为在HTML页面上呈现数据的一种方式。它工作得很好,但我需要在类中包含更多嵌套的HTML div来维护我的布局。有可能这样做吗?我有以下Javascript const productList = document.querySelector('#productList'); function renderProducts(doc) { let li = document.createElement('li'); let divInne
const productList = document.querySelector('#productList');
function renderProducts(doc) {
let li = document.createElement('li');
let divInner = document.createElement('div');
let title = document.createElement('h2');
li.setAttribute('data-id', doc.id);
title.textContent = doc.data().title;
li.appendChild(divInner);
li.appendChild(title);
div.setAttribute('class', 'inner');
document.body.appendChild(div);
productList.appendChild(li);
}
db.collection('Products').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
renderProducts(doc);
})
})
但是,这将生成以下HTML,其中显然没有嵌套任何内容*注:为了解释,我删除了数据
<ul id="productsList">
<li>
<div class="inner"></div>
<h2></h2>
</li>
</ul>
然而,我期望的结果是,然后以某种方式操纵DOM以在内部移动
看起来你在错误的地方添加了它。 请试试这个
function renderProducts(doc) {
let li = document.createElement('li');
let divInner = document.createElement('div');
let title = document.createElement('h2');
li.setAttribute('data-id', doc.id);
title.textContent = doc.data().title;
divInner.appendChild(title);
li.appendChild(divInner);
div.setAttribute('class', 'inner');
document.body.appendChild(div);
productList.appendChild(li);
}
您已经做了一点-如果希望在div中包含h2,请使用.appendChild-divInner.appendChildtitle,例如,将title附加到li。试着附加到div以得到你想要的。我想这就是我对li所做的。appendChilddivInner?如果document.body.appendChilddiv;零件已移除,它可以工作:当然。。谢谢你的帮助。我开始明白了。
function renderProducts(doc) {
let li = document.createElement('li');
let divInner = document.createElement('div');
let title = document.createElement('h2');
li.setAttribute('data-id', doc.id);
title.textContent = doc.data().title;
divInner.appendChild(title);
li.appendChild(divInner);
div.setAttribute('class', 'inner');
document.body.appendChild(div);
productList.appendChild(li);
}