I am trying to create multiple boxes from one box. But I am new to HTML, not know how to do it. What I need: I need one box; by clicking on it, two new boxes will create, and next time four boxes will create.
let elements = document.getElementsByClassName('box');
for(var i = 0; i < elements.length; i )
{
console.log(elements[i]);
}
.box {
width: 100px;
height: 100px;
border: 1px solid green;
background: steelblue;
}
<div ></div>
CodePudding user response:
You can try below code once I used jQuery
for it.
Here is code snippet:
$(document).on('click', '.box', function(){
$(".box").clone().eq(0).insertAfter( ".box" );
var i = 1;
$('.box').each(function() {
$(this).html(i);
i ;
});
});
.box {
width: 100px;
height: 100px;
border: 1px solid green;
background: steelblue;
display: inline-block;
margin: 4px;
font-size: 15pt;
text-align: center;
vertical-align: middle;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >1</div>
CodePudding user response:
This will increase boxes 2 from previews generated
if you like you can change box_num = 2 to box_num *= 2 that will increase boxes * 2 from previerws generated
let box_num = 2
let num = 1
$(document).on('click', '.box', function(){
let html = '';
for(let i = 0; i < box_num; i ){
html = `<div >${num 1}</div>`
num
}
$('.container').append(html)
box_num = 2
})
.box {
width: 100px;
height: 100px;
border: 1px solid green;
background: steelblue;
display: inline-block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ><div >1</div></div>
CodePudding user response:
Here is my attempt (vanilla JS) :
let boxesToCreate = 2;
createBoxesOnClick = (box) => {
box.addEventListener("click", () => {
for(let i = 0; i < boxesToCreate; i ){
let newBox = document.createElement("div");
newBox.classList.add("box");
newBox.textContent=boxesToCreate i;
createBoxesOnClick(newBox);
document.body.appendChild(newBox);
}
boxesToCreate = boxesToCreate * 2;
})
}
let firstBox = document.querySelector(".box");
createBoxesOnClick(firstBox);
body{
display:flex;
flex-wrap:wrap;
}
.box {
width: 100px;
height: 100px;
border: 1px solid green;
background: steelblue;
}
<div >1</div>
I'm not sure of the best way to register a new element to an event so I made a function to register new boxes to onClick
:
- I create x (
boxToCreate
) boxes - Add the
box
class - Add text to check the box number
- Register the box to onClick() with the function
- Append the new box to the container (body)
- Multiply
boxToCreate
by 2. Note that with your question we can't tell if you want to increase the number of created each time by x2 or 2, you just need to changeboxesToCreate = boxesToCreate * 2
byboxesToCreate = boxesToCreate 2
.