如何解决在元素内的元素内添加新元素
我才刚刚开始学习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,不能使用任何库或框架。
解决方法
foodNameP
将是NodeList
的数组,因为querySelectorAll
返回了
如果您确定div > div
仅在DOM中出现或最先出现,请执行此操作
foodNameP[0].append(foodName)
或者您可以在上面应用一个类。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。