jQuery
jQuery Add Remove Div Examples
Div manipulation is very helpful, especially when you are dealing with dynamic data. That said, to know how to add a div and/or to remove that div? If not, don’t worry. In this article, I am going to share with you, easy ways to use jQuery to add and to remove div by means of easy examples. So follow along to find out more.
How to use jQuery to Add Remove Div
Let’s assume that we have a div with ID “my_div1” in it. We would now like to add a div to this “my_div1”. The following example shows you how to do it easily:
Example – Add div & remove added div using jQuery
<class>
<head>
<title>Examples to Add a Div and Remove a Div using jQuery</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<style type="text/css">
#my_div1 {
background-color: #E1F3FF;
border: 1px solid #09F;
padding: 10px;
margin-bottom: 10px;
}
#my_div2 {
background-color: #9999FF;
border: 1px solid #90F;
padding: 10px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div id="my_div1">This is MY DIV 1</div>
<p>
<input type="submit" name="sbt_add2div1" id="sbt_add2div1" value="Add New Div to MY DIV 1">
<input type="button" name="sbt_reset" id="sbt_reset" value="Remove New Div from MY DIV 1">
</p>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
//This will add div to MY DIV 1
$('#sbt_add2div1').on("click", function(e){
$('<div id="my_div2" class="some_class">This is MY DIV 2</div>').appendTo('#my_div1');
e.preventDefault();
});
$('#sbt_reset').on("click", function(e){
$("#my_div2").remove();
e.preventDefault();
});
});
</script>
</body>
</class>Simple, isn’t it?
Do you know of any other ways to use jQuery to add remove div? Feel free to suggest by commenting below.