首页 > 解决方案 > 循环后添加特定元素

问题描述

所以我正在生成一个段落。我想<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>

标签: javascripthtml

解决方案


你想在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); 

}

推荐阅读