Last Updated: February 25, 2016
·
4.818K
· hiryu

JQuery: copy/clone element and increment index based on attribute

This snippet is for cloning #element and updating it's attributes if has a numeric index.

/**
 * jQuery plugin for copy/clone element and increment index 
 *
 * @version    0.1
 * @author     hiryu85
 *
 * Usage:
 *     $('input#article').copy().insertAfter( $('#destination') )
 *
 * Settings:
 *    - attributes      array Attribute to update
 *    - copyEvents  bool  Clone events handler?
 *
 */
(function(jQuery) {
    jQuery.fn.copy = function (options) {
        var $self    = this;
        var $_cloned = null;

        var _defaults = {
            attributes: ['id', 'name'],
            copyEvents: false,
        };
        var settings = jQuery.extend(_defaults, options);
        // Main
        var obj     = $(this);
        $_cloned    = jQuery(obj).clone(settings.copyEvents);
        var _childrens  = $_cloned.find('*');
        jQuery.each(_childrens, function (i, e) {
            var _oldId      = true;
            var _oldClass   = false;
            $e              = $(e);
            // Cerco indici nei seguenti attributi
            jQuery.each(settings.attributes, function (i, attrName) {
                try {   // Incremento indice numerico +1
                    var _content = $e.attr(attrName);
                    if (_content.match(/\d+/)) {
                        var _newContent = _content.replace(/\d+/i, function (index) {
                            return parseInt(index) + 1
                        });
                        $e.attr(attrName, _newContent);
                    }
                }catch(e){};
            });
        });
        // Chainable
        return $_cloned.each(function () {});
    }
})(jQuery);