Ash
Ash

Reputation: 169

How to create a new div with unique Id using jquery

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

Answers (6)

websky
websky

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

meteor
meteor

Reputation: 2568

You need to append another div dynamically to existing div by following way

$( "#test" ).append( '<div id="test2">Test</div>');

Upvotes: 4

Carlos V&#225;zquez
Carlos V&#225;zquez

Reputation: 388

$("#test2").appendTo("#test");

http://api.jquery.com/appendto/

Upvotes: 0

R4nc1d
R4nc1d

Reputation: 3113

Fiddle

var div2 = $("<div id='test2'>")
$("#test").append(div2)

Upvotes: 0

Louis Castro
Louis Castro

Reputation: 104

This is the easiest way I think

var Div_2 = $("<div></div>").attr("id","test 2");
Div_2.appendTo($("#test"))

Upvotes: 0

Aru
Aru

Reputation: 1870

Script

var contentString = "<div id='test2'></div>"
$("#test").append(contentString);

Upvotes: 1

Related Questions