Reputation: 11777
I am trying to clone multiple divs on my page by using the jQuery .clone()
method. The problem is, as soon as a div is cloned, it needs to have a unique ID. The cloned ID has to be there too. I was thinking I could keep the old ID and then just add a number on, increasing as more div's are on the page.
Example: base ID = one, so div one would be id
, then div two would be id-2
, then div three would be id-3
, etc.
Is this possible? My attempt at this is below:
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
$(target).clone().attr("id",id + $(id).size()).attr("class","drag").appendTo("body");
});
Each a
tag looks like this:
<a href="#one">One</a>
<a href="#two">Two</a>
Then the cloned element looks like this:
<div class="drag base" style="background-color:blue" id="one"></div>
<div class="drag base" style="background-color:green" id="two"></div>
Upvotes: 1
Views: 708
Reputation: 272106
Revised answer:
You can use the jQuery attribute starts with selector to keep a track of the clones, and their counts:
$("a").click(function() {
var targetId = $(this).attr("href").substring(1); // "one", "two"
var count = $("div[id^=" + targetId + "]").length; // initial value will be 1
$("#" + targetId).clone().attr("id", targetId + '-' + count).attr("class", "drag").appendTo("body");
});
Upvotes: 1
Reputation: 298176
You could do something like this:
$('a').addClass('link');
$('body').on('click', 'a', function() {
$(this).clone(true).attr('id', 'id-' + $('.link').length).appendTo('body');
});
Demo: http://jsfiddle.net/Em8PE/1/
Upvotes: 0
Reputation: 23796
See this: http://jsfiddle.net/3tu7V/1/
$(function(){
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
var click = $(target).data("clicked") || 0;
$(target).data("clicked", ++click);
$(target).clone().attr("id",id + click).attr("class","drag").appendTo("body");
});
});
I think this does what you want according to your comment: "Ah, is there any way for the element ID to be reset when the base ID is unique? Ex.) "If you clone div "one", it will produce "one-1", then "one-2", but if you then clone div "two", it will produce "two-3", not "two-1""
Upvotes: 2
Reputation: 14219
See this live example
var increment = 2;
$('a').live('click', function() {
$(this).clone().attr('id','id-' + (increment++)).appendTo('body');
});
Result:
Upvotes: 1
Reputation: 7031
i think in ur case $(id).size() will always be = 2. (only the last one and its clone will have the same id)
why don't you use a global variable var clickNumber
that you increment each time.
your code will be
var clickNumber = 0;
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
clickNumber ++;
$(target).clone().attr("id","id-" + clickNumber).attr("class","drag").appendTo("body");
});
Upvotes: 1