Hoping this isnt a repeat question as I could not find an answer.
I have a div that I need cloned.
<div class="phoneBookEntriesContainer">
content here
</div>
I have to add an ID afterwards…dont ask :P.
<script type="text/javascript">
var i = 1;
$(".phoneBookEntriesContainer").attr("id","phoneBookEntries" + i);
var doSomething = function(){
$(".phoneBookEntriesContainer").attr("id","phoneBookEntries" + i);
$("#phoneBookEntries" + i).clone().insertAfter("#phoneBookEntries" + i);
i ++;
};
</script>
The code above kinda works, but instead of giving my divs unique id’s, it replaces all of them with the same id.
So at the start I would have one #phoneBookEntries1 div, after clicking the button to run the function I have two #phoneBookEntries2 divs etc etc.
$(".phoneBookEntriesContainer")returns an array of all DOM elements that have the classphoneBookEntriesContainer. Thus when you useattr, it replaces the id on all of those elements. If you want to replace it on a specific element only, you need to specify which one.You can do that in the following ways:
To achieve what you want, you should loop over all elements using jQuery’s
.each()method. For details, see Hidde’s answer.If you want to clone your div and give it a new ID everytime, use a variable to keep track of the number to be appended.
See the demo here
This is the Jquery code