Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create div dynamically using jQuery?
To create a div dynamically using jQuery, you can use several methods such as html(), append(), or create elements with the $(<div>) constructor. The html() method replaces the existing content, while append() adds new content to existing elements.
Example 1: Using html() Method
The following example shows how to create a div dynamically using the html() method on button click −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("body").html("<div>This is a new div.</div>");
});
});
</script>
</head>
<body>
<button>Create a new div</button>
<p>This is demo text.</p>
</body>
</html>
Example 2: Using append() Method
If you want to add a div without replacing existing content, use the append() method −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#addDiv").click(function(){
$("body").append("<div style='border: 1px solid blue; padding: 10px; margin: 5px;'>New div added!</div>");
});
});
</script>
</head>
<body>
<button id="addDiv">Add New Div</button>
<p>This content will remain when new divs are added.</p>
</body>
</html>
Example 3: Creating Div with jQuery Constructor
You can also create a div element using the jQuery constructor and then append it −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#createDiv").click(function(){
var newDiv = $("<div>", {
text: "Dynamically created div with attributes",
css: {
"background-color": "#f0f0f0",
"padding": "15px",
"margin": "10px",
"border": "2px solid green"
}
});
$("body").append(newDiv);
});
});
</script>
</head>
<body>
<button id="createDiv">Create Styled Div</button>
<p>Click the button to create a styled div element.</p>
</body>
</html>
These methods give you flexibility to create div elements dynamically based on your requirements, whether you need to replace content or add new elements to your page.
Advertisements
