Reputation: 169
Apologies if this has already been asked. There are similar questions but none seemed to explain the best way of doing this.
Say i have the following code:
<div id ="test"> hello </div>
And i want to insert a new div box with id "test 2" within this div. What would be the easiest method using Jquery?
Upvotes: 0
Views: 70
Reputation: 3172
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
var divCount = 0;
$( "#create" ).click(function() {
$( "#contents" ).append( '<div id="div' + divCount + '">div id=div' + divCount + '</div>');
divCount++;
});
});
</script>
</head>
<body>
<div id="contents"></div>
<a href="#" id="create">Add new div</a>
</body>
</html>
Upvotes: 0
Reputation: 2568
You need to append another div dynamically to existing div by following way
$( "#test" ).append( '<div id="test2">Test</div>');
Upvotes: 4
Reputation: 388
$("#test2").appendTo("#test");
http://api.jquery.com/appendto/
Upvotes: 0
Reputation: 104
This is the easiest way I think
var Div_2 = $("<div></div>").attr("id","test 2");
Div_2.appendTo($("#test"))
Upvotes: 0
Reputation: 1870
Script
var contentString = "<div id='test2'></div>"
$("#test").append(contentString);
Upvotes: 1