javascript - how to append the button to each
问题描述
I want to append the button
tag to each of the 6 li
tags using a forEach
loop but after running the below code I am only getting a button
tag on the 6th (last) li
tag. Please help and let me what I am doing wrong.
var button = document.createElement('button');
button.appendChild(document.createTextNode('delete'));
var spam = document.createElement('spam');
var li = document.querySelectorAll('li');
li.forEach(function(i) {
i.appendChild(button);
});
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter" width='50px'>Enter</button>
<ul>
<li class="bold red" random="23">Notebook</li>
<li>Jello</li>
<li>Spinach</li>
<li>Rice</li>
<li>Birthday Cake</li>
<li>Candles</li>
</ul>
</body>
解决方案
Just move document.createElement('button')
in forEach Loop
of yours
var spam = document.createElement('spam');
var li = document.querySelectorAll('li');
li.forEach(function(i) {
var button = document.createElement('button');
button.appendChild(document.createTextNode('delete'));
i.appendChild(button);
});
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter" width='50px'>Enter</button>
<ul>
<li class="bold red" random="23">Notebook</li>
<li>Jello</li>
<li>Spinach</li>
<li>Rice</li>
<li>Birthday Cake</li>
<li>Candles</li>
</ul>
</body>
推荐阅读
- android - 折叠工具栏,下方有 16:9 图像和文本
- xml - 将 WrappedArray 拆分为多行和多列
- angular - 具有图像动作/效果模式的 Ngrx 实体
- interactive - 如何在 Altair 图表中将公式作为“x 变量”传递?
- r - 如何编辑自己的 k-means 函数,以便将簇作为输入而不是 R 中的中心?
- c++ - 对时间复杂度与哈希映射的混淆
- google-cloud-platform - GKE Secrets 或 Google 机密管理器
- python - 获取具有特定角色 discord bot 的所有成员的列表
- php - 获取 Facebook 图片 URL
- tfs - Tfs 工作项搜索不返回包含