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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With