Using append my innerdiv is attaching only one WHEAT-COLORED-BOX*; while using appendTo my innerdiv is attaching all the required number of WHEAT-COLORED-BOXES. Thus, for my case appendto is giving right result while append fails to do so!
$(()=>{
$('button').click(function appendizing(){
for(let i=1; i<=9; i)
$('<div></div>').addClass('box').css("backgroundColor", "wheat").appendTo('.container');
});
});
.container{
font-size: 0px;
border: 1px solid blue;
width: 120px;
height: 120px;
}
.box{
display: inline-block;
width: 40px;
height: 40px;
border-radius: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
<button>appendDiv</button>
now look at this APPEND method usage ->
$(()=>{
$('button').click(function appendizing(){
for(let i=1; i<=9; i)
$('.container').append('<div</div>').addClass('box').css("backgroundColor", "wheat");
});
});
.container{
font-size: 0px;
border: 1px solid blue;
width: 120px;
height: 120px;
}
.box{
display: inline-block;
width: 40px;
height: 40px;
border-radius: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
<button>appendDiv</button>
What is the reason for this. Kindly explain...
CodePudding user response:
Check This
$(()=>{
$('button').click(function appendizing(){
for(let i=1; i<=9; i)
$('.container').append($('<div></div>').addClass('box').css("backgroundColor", "wheat"));
});
});
.container{
font-size: 0px;
border: 1px solid blue;
width: 120px;
height: 120px;
}
.box{
display: inline-block;
width: 40px;
height: 40px;
border-radius: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
<button>appendDiv</button>
CodePudding user response:
You are closing tag on new div
that you are appending
$(()=>{
$('button').click(function appendizing(){
for(let i=1; i<=9; i)
$('.container').append($('<div></div>').addClass('box').css("backgroundColor", "wheat"));
});
});
.container{
font-size: 0px;
border: 1px solid blue;
width: 120px;
height: 120px;
}
.box{
display: inline-block;
width: 40px;
height: 40px;
border-radius: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
<button>appendDiv</button>
CodePudding user response:
- You forgot to close the div tag
- You are adding class and style to the container, not to the appending div-s. You can specify it inline on append or create element and then append it.
$(()=>{
$('button').click(function appendizing(){
for(let i=1; i<=9; i)
$('.container').append('<div style="background-color: wheat;"></div>');
});
});
.container{
font-size: 0px;
border: 1px solid blue;
width: 120px;
height: 120px;
}
.box{
display: inline-block;
width: 40px;
height: 40px;
border-radius: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
<button>appendDiv</button>