javascript - 循环后添加特定元素
问题描述
所以我正在生成一个段落。我想<ul>
在第 3 段下添加。
这是代码片段:
var i = 0;
for (i = 0; i < 5; i++) {
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
const element = document.getElementById("div1");
element.appendChild(para);
// add ul under the 3rd paragraph
}
.nav {
background-color: grey;
text-align: center;
width: 90px;
height: 90px;
margin: 0;
padding: 0;
transition: background .5s;
/* .5s how long transition should take */
}
<ul class="nav">
<p>Test</p>
</ul>
解决方案
你想在id1元素的第3段下注入ul吗?你可以有类似的东西:
// On your "add ul under the 3rd paragraph line
if (i == 2){ //Condition for 3rd paragraph (-1 as the loop starts on 0)
const menu = document.getElementsByClassName("nav")[0]; //get the ul you want to add. getElementsByClassName returns a list, so would need to get the item you want to add. You might want to use an id in case you have multiple elements with class nav.
//Finally, add the element on your div1
document.getElementById("div1").appendChild(menu);
}
推荐阅读
- java - Java中具有不同数据类型的复合减法
- java - 在任务仍在运行时返回结果
- javascript - 为什么我的自动聊天框不显示?
- php - file_put_contents() 无法打开流式输入:MacOS 上的权限被拒绝
- linux - ngork 的权限被拒绝,并且没有创建直接链接
- python - 用beautifulsoup和python抓取按钮点击时取消隐藏的文本?
- node.js - 循环前执行脚本(Heroku node.js discord bot)
- apache-kafka - 获取每个组的 Kafka 消耗时间
- javascript - 如何为启动时间过长的 create-react-app 启用 eslint 缓存?
- port - Artifactory 7.21.12 URL 从 8081 重定向到 8082