CSS grid layout:
.wrapper {
display: grid;
grid-template-areas: "btn1 btn2 btn3 btn4";
grid-template-columns: repeat(4, 1fr);
}
#btn {grid-area: "btn1"}
#btn2 {grid-area: "btn2"}
#btn3 {grid-area: "btn3"}
#btn4 {grid-area: "btn4"}
created by div and button:
const div = document.createElement("div");
div.classList.add("wrapper");
const body = document.body;
body.appendChild(div);
const button = document.createElement("button");
button.textContent = "Click1";
button.setAttribute("id", "btn");
Next, I want to create three more buttons based on the first one and paste them into their respective areas. If you stupidly describe each action:
const b2= button.cloneNode(true);
const b3= button.cloneNode(true);
const b4= button.cloneNode(true);
b2.setAttribute('id', 'btn2');
b3.setAttribute('id', 'btn3');
b4.setAttribute('id', 'btn4');
b2.textContent = "Click" 2;
b3.textContent = "Click" 3;
b4.textContent = "Click" 4;
div.appendChild(button);
div.appendChild(b2);
div.appendChild(b3);
div.appendChild(b4);
How to do it optimally? Something like this (doesn't work):
let b2, b3, b4;
let arr = [b2,b3,b4]
let i=2;
while(i<5){
for(let j=0; j<arr.length; j ){
arr[j].setAttribute('id', 'btn' i);
arr[j].textContent= "Click" i;
div.appendChild(arr[j])
} i }
CodePudding user response:
There's no need for the repetition, or for the clone
, just a single for
loop. Here using a documentFragment to avoid multiple insertions into the DOM.
const div = document.createElement('div');
div.classList.add('wrapper');
document.body.appendChild(div);
const buttonCount = 4
const buttonFragment = document.createDocumentFragment();
for (let i = 1; i <= buttonCount; i ) {
const button = document.createElement('button');
button.textContent = `Click${i}`;
button.id = `btn${i}`;
buttonFragment.append(button);
}
div.append(buttonFragment);
.wrapper {display: grid; grid-template-areas: "btn1 btn2 btn3 btn4"; grid-template-columns: repeat(4, 1fr);}
#btn1 {grid-area: "btn1"; background-color: pink;}
#btn2 {grid-area: "btn2"; background-color: aquamarine;}
#btn3 {grid-area: "btn3"; background-color: gray;}
#btn4 {grid-area: "btn4"; background-color: salmon;}
CodePudding user response:
Using insertAdjacentHTML
simplifies the task. Something like:
document.body.insertAdjacentHTML(`beforeend`, `<div id="buttons">`);
const bttnDiv = document.querySelector(`#buttons`);
const nButtons = 5;
for (let i = 1; i < nButtons 1; i = 1) {
bttnDiv.insertAdjacentHTML(
`beforeend`,
`<button id=btn${i}>Click ${i}</button>` );
}
button {margin-right: 3px;}
#buttons {
border: 1px solid #ddd;
padding: 0.3rem;
width: 50vw;
text-align: center;
}
CodePudding user response:
for(let i = 0; i < 5; i){
const btn = const button = document.createElement('button');
btn.setAttr()
btn.textContent = something
div.appendChild(btn)
}
// maybe just like this?