Monday, July 3, 2023

How to dynamically create a div in jQuery? Example

Many times you need to create an HTML element and dynamically add that into DOM without reloading the page. The traditional way of doing this is by using JavaScript's innerHtml() function but jQuery provides better ways to achieve the same effect. You can use jQuery DOM manipulation methods like append(), appendTo() or html() to add new HTML elements like div, paragraph, headings, image into DOM without reloading the page again. In this tutorial, I will show you how to dynamically create a div and add that into a page by using pure jQuery.

In order to do this, we need to first create the element and that find the right place to add that element, which depends upon your requirement and finally, we need to add that element using append(), appendTo() or html() jQuery methods.


jQuery example to dynamically add a div on page

In this example, we have a div with id board and a button to add new divs into this board. In $(document).ready() we have bound an event listener to click event, which means when the user will click on this button, new divs will be created and added into the board. For easy identification, I have made the background color of new divs as red. Just click the button and a new div will appear on your page.

In this example, I am using the append() function to add the divs. First, I am selecting our existing div by using ID selector i.e. $("#board") and then calling append() with HTML to add new divs. This method adds the new divs below the selected node.

Here is an example:

<html>
<head>
<title>How to dynamically add a div using jQuery</title>
<style type="text/css">
.box {
background-color: red;
width: 100px;
height: 100px 
}
</style>
</head>

<body>

<h2>How to dynamically add an HTML element using jQuery</h2>

<div id="board">The Board is Empty, now add some div on it</div>

<button id="btn_add">Add a Div</button>


<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script>
$(document).ready(function() {

$("#btn_add").click(function() {
$("#board").append("<div class='box'> Just added div </div>");
});

});
</script>

</body>
</html>


jQuery in Action

When you save this HTML page in VS Code or any of your IDE or even on a notepad and open it on your browser you will see following screen:

How to dynamically create a div in jQuery? Example



And when you click the "Add a Div" button, it will add a new div element in your DOM and refresh the browser and you can see the below:

How to create a div in jQuery at runtime


That's all about how to dynamically add new HTML elements using jQuery. In this example, we have added div element but you can theoretically add any element by following this technique. You can also use appendTo() or html() function instead of append().


All the best

No comments :

Post a Comment