简体   繁体   中英

How to wrap each divs to multiple elements

This is how it is:

<button> One <button> 
<button> Two <button> 
<button> Three <button>     

what I'm trying to do is like this:

<div><button> One <button></div> 
<div><button> Two <button></div>   
<div><button> Three <button></div>   

Javascript:

var theDivs = document.createElement("div");

var divWrapper = new Array(3).fill(theDivs);

for (var i = 0; i < divWrapper.length; i++) {

  divWrapper[0].appendChild(buttonOne);
  divWrapper[1].appendChild(buttonTwo);
  divWrapper[2].appendChild(buttonThree);

  document.body.appendChild(divWrapper[0]);
  document.body.appendChild(divWrapper[1]);
  document.body.appendChild(divWrapper[2]);

};

You need to create separate <div> elements, one on each loop iteration, or else all of the array elements will be the same <div> .

Here's what you're doing:

var divWrapper = new Array(3).fill(theDivs);

This means all three elements of the divWrapper array are the reference to the same <div> object, which you don't want.

Also, you can create DRY-er code by only creating and appending elements once, inside the loop, instead of copying it three times like you do here:

divWrapper[0].appendChild(buttonOne);
divWrapper[1].appendChild(buttonTwo);
divWrapper[2].appendChild(buttonThree);

document.body.appendChild(divWrapper[0]);
document.body.appendChild(divWrapper[1]);
document.body.appendChild(divWrapper[2]);

Demo:

 for (var i = 0; i < 3; i++) { var divWrapper = document.createElement("div"); var button = document.createElement("button"); button.textContent = i + 1; divWrapper.appendChild(button); document.body.appendChild(divWrapper); }; 
 div { /* make <div>s clearer */ background-color: grey; margin: 1em; } 


As per your comment, below is a demo to show you what will happen if you do it your way, filling an array with one element. Although you are accessing different elements of the array with divWrappers[i] in the loop, they all refer to the same object, so that all the buttons are added to the same <div> .

 var divWrapper = document.createElement("div"); var divWrappers = Array(3).fill(divWrapper); for (var i = 0; i < divWrappers.length; i++) { var button = document.createElement("button"); button.textContent = i + 1; divWrappers[i].appendChild(button); document.body.appendChild(divWrappers[i]); }; 
 div { background-color: grey; margin: 1em; } 

Try using jQuery's .wrapAll()

Include jQuery in your HTML (see the website above if you need further information on how to do that).

Then use:

$(":button").wrapAll("<div class=''/>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM