且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

forEach循环在li标签内的div中插入名称

更新时间:2023-12-05 07:55:10

只需在div,并在每次迭代中将其附加到文档中。



  var elements = [ 'rock','paper','scissor']; demoP = document.getElementById( demo); elements.forEach(function(item,index){newlistitem = document.createElement( li); newdiv = document.createElement( div); newdiv.setAttribute( style, border:5px solid black;) ; newdiv.setAttribute( id, div_demo); newdiv.innerHTML = index [ + index +]: + item +< br>; demoP.appendChild(newlistitem); newlistitem.appendChild( newdiv);});  

 < ul> < p id = demo>< / p>< / ul>  



希望有帮助!


var elements = ['rock', 'paper', 'scissor'];
demoP = document.getElementById("demo");

elements.forEach(function(item, index) {
  demoP.innerHTML = demoP.innerHTML + "index[" + index + "]: " + item + "<br>";
});

<ul>
  <li>
    <div style="border: 5px solid black;" id="div_demo">
      <p id="demo"></p>
    </div>
  </li>
</ul>

Hi,

I'm new to JavaScript. I want to display array names in separate div tag inside li. So far I have managed to get array list to display one below another in single div & li. I want to display each name in separate div inside li.

Just add every li in a div and append it to the document in every iteration.

  

var elements = ['rock', 'paper','scissor'];
  
  demoP = document.getElementById("demo");
  elements.forEach(function(item, index) {
  
  newlistitem = document.createElement("li"); 
  newdiv = document.createElement("div");
  newdiv.setAttribute("style", "border: 5px solid black;");
  newdiv.setAttribute("id", "div_demo");
	
  newdiv.innerHTML = "index[" + index + "]: " + item + "<br>";
  
  demoP.appendChild(newlistitem);
  newlistitem.appendChild(newdiv);

});

<ul>	
  <p id="demo"></p>
</ul>

Hope this helps!!