jQuery Add Div Examples
jQuery is a much “fun” JavaScript framework and I love it as it lets you do a lot in a snap! That said, have you ever wondered how to easily add a div to the web page? If not, then this article is for you. In this article, I am going to show how to use jQuery to add a div along with easy to follow examples.
How to add div using jQuery
So let’s jump right in and let’s see how you can do this using an example. In this example, I am assuming that I have a div with ID “my_div”. I need to add this div now to another element in my page. This element could be another div, an image, etc. Because the way a div can be added to an element varies depending upon the type of the element that the div has to be added to, I am going to give out the basic way to add a div in this article. In later articles, I am going to cover how specifically a div can be added to specific elements.
Using jQuery to Add Div
I suggest you try the demo first to visualize things as it helps for better understanding. Now in the demo, we can see that there is a div with some text in it. When you click on the “Add” button, the background color of the div changes to red. Why does this happen? This happen because of 2 reasons:
- We are adding a new div to an existing div.
- To visualize the change and to confirm that the div is being added, we are applying background color to the new div and hence when the new div gets added to the existing div, the background color will be automatically added to the existing div.
Note: If the existing div already has a background color (say green), even though the new div has a background color of red, when it is added to the existing div, the existing div will continue to show the green color. Does that mean that there is something wrong? Well, no. Because the existing div already has a similar style already applied to it, that style will be given more weight than the new style being added & hence the existing div will continue to display it’s existing background color. But rest assured that the new div is added, so don’t worry about not being about to change in the background color for the existing div.
Example: Adding a div using jQuery
<html>
<head>
<title>Example for adding div using jQuery</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
<div id="my_div">This is my existing div. </div>
Click on "Add" to add a div to the div above.
<input type="submit" name="sbt_add" id="sbt_add" value="Add">
<input type="submit" name="sbt_remove" id="sbt_remove" value="Remove">
<script type="text/javascript">
$('#sbt_add').on("click", function(e){
$('#my_div').add('<div id="new_div">This is a new div.</div>').css('background-color', 'red');
e.preventDefault();
});
$('#sbt_remove').on("click", function(e){
$('#my_div').removeAttr('style');
e.preventDefault();
});
</script>
</body>
</html>Your Turn!
Do you know of any other ways to use jQuery to add div? Feel free to suggest by commenting below.