1

I want to clone a element with id abc to abc1,abc2,abc3 etc when I click the element with abc id.

Here is the code I am trying which isn't working :(

<html><body>
 <p onclick="aa()" id="abc">HEEYYEYEY</p>
 <p id="xx"></p>
</body>
<script>
var temp=0;
function aa(){
 temp=temp+1;
 document.getElementById("xx").innerHTML=temp;
 $('#abc').clone().appendTo('#abc'+temp);
}
</script>
</html>

Please help. What am I doing wrong? And is there any way so that I can place these cloned elements to somewhere specific I want (say below some image or after a paragraph with id pr)

Thanks in advance.

NOTE: question updated (class="abc has been changed to id="abc")(still not working)

  • https://api.jquery.com/clone/ "Note: Using .clone() has the side-effect of producing elements with duplicate `id` attributes". you need to clone into a new variable, change the id of the element in that new variable, then insert it into the dom. e.g. `foo = el.clone(); foo.id = 'new unique id'; foo.appendTo(...);` – Marc B Nov 10 '15 at 14:50
  • You have no `id=abc` in html shown ... or `id=abc1,abc2 etc`. A proper explanation of what you are expecting this code to do would help – charlietfl Nov 10 '15 at 14:50
  • Possible duplicate of [How to JQuery clone() and change id](http://stackoverflow.com/questions/10126395/how-to-jquery-clone-and-change-id) – Daniel B Nov 10 '15 at 14:51
  • you use `$('#abc')` and there is no element with ID `abc`, only with `class` `abc` – areim Nov 10 '15 at 14:51
  • 1
    Also you're using a jQuery-function without even including jQuery. – Michael B Nov 10 '15 at 14:52
  • 1
    You append your new element to abc1 in the first iteration but your id is just abc – David P. Nov 10 '15 at 14:58
  • 1
    Explain what expected results are. it is still not clear what you are wanting to do. The target elements you are trying to append to don't exist – charlietfl Nov 10 '15 at 15:09

2 Answers2

0

You append the element to #abc0 (and so on) but there are no elements with those ids. Try to append your elements to the body.

David P.
  • 370
  • 1
  • 13
0

when you clone, set your attribute id to whatever you want it to. then append to the #xx div like so:

$(document).ready(function() {
    var count = 0;
 $('#abc').on('click', function() {
        count++;
     var newItem = $(this).clone().attr('id', 'abc' + count);
        $('#xx').append(newItem);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="abc">HEEYYEYEY</p>
<p id="xx"></p>

ps. youre using both vanilla javascript and jquery at the same time. it would be easier to maintain and read if you stuck to one

indubitablee
  • 8,136
  • 2
  • 25
  • 49