1

I have tried to write a very simple code of jquery to append an element. Here is an example code -

<script type="text/javascript">
var v=$("strong");
  $(document).ready(function(){
            $("button").click(function(){

                    $(".c1").append($ (v) );

            });
        });
</script>

What happens here, the content of <div class="c1"> appears just once with multiple click. Instead of jQuery object, if I put html content then it appears as many as I click the button. I want to do the same thing with Object.

I started learning jQuery just today. So any sort of suggestion will be helpful.

1 Answer 1

5

change this line:

$(".c1").append(v.clone());

If you want it to append the same node multiple times you need to either dynamically create that node, or clone the existing one.

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

2 Comments

I'm afraid that loop is not working here. For example - $("button").click(function(){ for(x=1;x<=3;x++){ $(".c1").append($(".testDiv").clone()); } }); ----------- here the div should appear 3 times. Instead, it's appearing 7 times. Any suggestion please?
because you are using $().clone() it will get all class="testDiv" on the page. If you want it to only use the ones that are there when the page loads make a variable, and myVariable.clone()

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.