Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery clone last element from each list row

I'm trying to clone last element from each list row. I can clone rows(i need to clone first element in this case), but I can't clone last span from each li. Here is what I have so far:

HTML:

<ul class="elements">
    <li>
        <span>Span 1</span>
        <span>Span 2</span>
        <span>Span 3</span>
    </li>
    <li>
        <span>Span 4</span>
        <span>Span 5</span>
        <span>Span 6</span>
    </li>
</ul>
<a href="#" class="new_row">Add new row</a>
<a href="#" class="new_column">Add new column</a>

JQuery:

$('.new_row').click( function(e) {
    e.preventDefault();
    var ul = $(this).prev('.elements');

    var new_data= $("li", ul).eq(0).clone();
    new_data.appendTo(ul);
});
$('.new_column').click( function(e) {
    e.preventDefault();
    $('li').each(function(){
        $('span:last').clone();
    });
});

JSFiddle: http://jsfiddle.net/vPDpH/

I would appreciate any help. Thank in advance.

like image 209
Andrei Surdu Avatar asked Mar 05 '26 12:03

Andrei Surdu


2 Answers

You are cloning the element but not doing anything with it ..

Also you need to clone the last span in the context of current li. Otherwise it will clone the last span in the HTML irrespective of where it is

$('.new_row').click( function(e) {
    e.preventDefault();
    var ul = $(this).prev('.elements');

    var new_data= $("li", ul).eq(0).clone();
    new_data.appendTo(ul);
});
$('.new_column').click( function(e) {
    e.preventDefault();
    $('li').each(function(){
       var new_data= $('span:last', this).clone();
        new_data.appendTo(this);
    });
});

Check Fiddle

like image 143
Sushanth -- Avatar answered Mar 08 '26 01:03

Sushanth --


An alternative

Javascript

$(".new_row").click(function (e) {
    e.preventDefault();
    var elements = $(e.target).siblings(".elements").first();

    elements.append($("li", elements).first().clone());
});

$(".new_column").click(function (e) {
    e.preventDefault();
    $("li", $(e.target).siblings(".elements").first()).each(function (index, element) {
        $(element).append($("span", element).last().clone());
    });
});

On jsfiddle

like image 43
Xotic750 Avatar answered Mar 08 '26 02:03

Xotic750



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!