David Debnar
David Debnar

Reputation: 125

Cloning an element multiple times

I have a li element parented to a div with id holder. I need to clone the li multiple times, have all the clones parented to the holder div and change their data-ids. My hierarchy looks like this:

<div id="holder">
    <li data-id=0 class="element">
        //other nodes
    </li>
</div>

How can I clone the li element and than change it's data-id so I get:

<div id="holder">
    <li data-id=0 class="element">
        //other nodes
    </li>
    <li data-id=1 class="element">
        //other nodes
    </li>
    <li data-id=2 class="element">
        //other nodes
    </li>
    <li data-id=3 class="element">
        //other nodes
    </li>
    <li data-id=4 class="element">
        //other nodes
    </li>
    <li data-id=5 class="element">
        //other nodes
    </li>
</div>

-- David

Upvotes: 2

Views: 3188

Answers (3)

MassivePenguin
MassivePenguin

Reputation: 3711

Here's a quick and dirty solution:

http://jsfiddle.net/Epzt9/7/

Also - and I'm surprised no-one else has mentioned this - your containing element for the list items should be a <ul>, not a <div> - <li> tags don't stand on their own, they should belong to a list.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074148

Just use clone and attr:

var holder, li, clone, counter;
holder = $("#holder");
li = holder.find("li:first");
counter;
for (counter = 1; counter <= 5; ++counter) {
    clone = li.clone();
    clone.attr("data-id", counter);
    clone.appendTo(holder);
}

Upvotes: 3

James Allardice
James Allardice

Reputation: 165951

Something along these lines should work:

var clone = $("#holder > li").last().clone();
clone.data("id", parseInt(clone.data("id"), 10) + 1);
$("#holder").append(clone);

It gets a reference to the last li child of #holder and clones that. It then adds 1 to the current value of the data-id attribute, and appends the clone back into #holder.

However, this won't actually change the value of the attribute on the element (if you inspected the DOM, clones would appear to have the same data-id value as the element from which they came). The new value is associated with the element, which is fine if you are using the jQuery data method to obtain this value later. If not, you would need to use attr instead of data to set the value.

Upvotes: 0

Related Questions