我才刚刚开始学习Javascript,可以为遇到的这个问题提供帮助。我目前正在尝试使用DOM操作在另一个div标签中的div标签中添加p标签。
<div class='xxx'>
<div> <-- I was able to create this div through DOM manipulation
<p></p> <!-- Trying to add this tag through DOM manipulation
<p></p> <!-- Trying to add this tag through DOM manipulation
<p></p> <!-- Trying to add this tag through DOM manipulation
</div>
</div>
我在Stackoverflow上进行了搜索,但找不到我想要的东西。到目前为止,这是我在其他几种方法中尝试过的方法。
Was able to create div here:
const mainFoodDiv = document.querySelector('.food-names')
for (let i = 0; i < foodCategoryArr.length; i++) {
const foodName = document.createElement('div')
mainFoodDiv.append(foodName)
}
Getting an error that says foodNameP.append is not a function:
const foodNameP = document.querySelectorAll('div > div')
for (let i = 0; i < foodCategoryArr.length; i++) {
const foodName = document.createElement('p')
foodName.textContent = foodCategoryArr[i]
foodNameP.append(foodName)
}
有人可以指导我从这里去哪里吗?我只能为此使用纯JavaScript,不能使用任何库或框架。
答案 0 :(得分:1)
foodNameP
将是NodeList
的数组,因为querySelectorAll
返回了
如果您确定div > div
仅在DOM中出现或最先出现,请执行此操作
foodNameP[0].append(foodName)
或者您可以在上面应用一个类。