jQuery

jQuery Remove Div Examples

It’s really good to know you can do virtually anything when using jQuery. Be either DOM manipulation or changing  appearance of something, adding animation, etc. The most basic of them is div manipulation. So let’s say you have added a div or there’s an existing div on a page. Do you know how to remove this div using jQuery? Well, don’t worry if you don’t. In this article, I am going to share how to remove a newly added div or an existing div using jQuery.

How to use jQuery to remove div

Let’s assume that we have a web page  with a pre-existing div with ID “my_div1” in it. Now this also contains another div with ID “my_div2”, as part of it’s content.  We would now like to remove this div “my_div2”. The following example shows you how to do it easily:

Example – Easily remove div using jQuery

<html>
<head>
<title>Examples to 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: #D7FFD7;
	border: 1px solid #090;
	padding: 10px;
	margin-bottom: 10px;	
}
</style>
</head>

<body>

<div class="divs_container">

<div id="my_div1">This is MY DIV 1

	<div id="my_div2">This is MY DIV 2</div>

</div>

</div>

<p>	
<input type="submit" name="sbt_remove" id="sbt_remove" value="Remove the DIV 2">

<input type="button" name="sbt_reset" id="sbt_reset" value="Reset everything">
</p>

<script type="text/javascript" language="javascript" >

$(document).ready(function(){

//Ignore this	
var divs_container_html = $(".divs_container").html();	

	//This will remove the div from  MY DIV 1
	$('#sbt_remove').on("click", function(e){		

		$("#my_div2").remove();

		e.preventDefault();

	});	

	//IGNORE THIS: Reset the divs back to their original state
	$('#sbt_reset').on("click", function(e){

		$(".divs_container").html(divs_container_html);

		e.preventDefault();

	});		

});	

</script>
</body>
</html>

When you run the above code, simply click on the Remove the DIV 2 button to remove the div to body. To reset it or to add it back, you can use the code associated with the Reset button.

Note:

You can use the same method to remove the div, even if it is a static div or a dynamic div.

Simple, isn’t it?

Do you know of any other ways to use  jQuery to remove div? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*