1

Kindly notify me I am explaining it well or not. I'm using .append() to repeat a div inside a page.

HTML

 <html>
 <head>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
 <script>
  $(document).ready(function(){
    $("#num").click(function () {
      $('#form').append("<div class='Box'>I'm new box by prepend</div>");   
    });
  });
  </script>
  </head>

  <body>
    <div id="form">
       Hai Add Another by clicking the button
    </div>
    <button id="num">Click Me</button>
  /body>
 </html>

This works good when I add a div repeatedly. But I like to call it externally like the below code.

 <html>
  <head>
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
   <script>
    $(document).ready(function(){
      $("#num").click(function () {
        $('#form').append($('#Box'));   
      });
    });
  </script>
  </head>

  <body>
  <div id="form">
  Hai Add Another by clicking the button
  </div>
  <div class='Box'>I'm new box by prepend</div>
  <button id="num">Click Me</button>
 /body>
 </html>

Why is this not working?

3 Answers 3

3

Try using clone():

 <html>
 <head>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
 <script>
  $(document).ready(function(){
  $("#num").click(function () {
  $(".Box:first").clone().appendTo("#form"); 
});
});
  </script>
  </head>

  <body>
  <div id="form">
  Hai Add Another by clicking the button
  </div>
  <div class='Box'>I'm new box by prepend</div>
  <button id="num">Click Me</button>
 </body>
 </html>​

You have to create a new element before adding it.

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks man but clone() repeats all the previous divs created inside. i just want to add only one div per click. Is there any other solution for it.
if i use a inputbox the same value inside it gets repeated due to clone() is there any other way to avoid it?
3

try this

 $(document).ready(function(){
    $("#num").click(function () {
       $(".Box").first().clone().appendTo("#form"); 
    });
 });

1 Comment

if you think the code helped you and its working, keep the answer as accepted as it might help for the future viewers also.
1

Try something like this:-

 $("#parent_div").append('<div id="created_div"></div>');

2 Comments

i want to add a div externally from html page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.