Skip to content

Instantly share code, notes, and snippets.

@crswll
Last active December 13, 2015 17:19
Show Gist options
  • Save crswll/4946635 to your computer and use it in GitHub Desktop.
Save crswll/4946635 to your computer and use it in GitHub Desktop.
Just a quick demo for cloning and removing elements and updating their id for someone in IRC.
(function($){
$('.add').on('click', function(){
var $items = $('.items'),
$last = $items.find('.item').last();
$clone = $last.clone();
$clone.attr('id', function(idx, id){
return id.replace(/\d+$/, function(digit){
return +digit + 1;
});
}).val($clone.attr('id'));
$clone.appendTo($items);
});
$('.remove').on('click', function(){
$('.items .item').last().remove();
});
})(jQuery);
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div class="items">
<input class="item" value="id-1" id="id-1">
</div>
<button class="add">Add</button>
<button class="remove">Remove</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment