Increase element ID by one after every click?

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>

Answers


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""


Need Your Help

Accessing an element with no attributes in Watir

automation automated-tests watir watir-webdriver webautomation

Using Watir, is there a way to access an element without attributes?

Prefix headers in other IDEs than Xcode

c visual-studio c++11 compilation qt-creator

The prefix header functionality in Xcode comes in handy quite often and I was wondering if other IDEs provide a similar functionality? Or is there even a way on compiler level?

Function name is used as SQL query

php cakephp cakephp-1.3

I've got a problem very similar to the ones found here and here, but these solutions aren't helping me fix my version of the problem. I'm using CakePHP 1.3 and I'm trying to call some model functions