Question

I am trying to make my own clone function, but am running into a problem. I can use jQuery's clone function in my own without problem like this:`

$.prototype.cloneDumpingEvents = function () {
    return $(this).clone();
};

(Or, see it in action: http://jsfiddle.net/Shawn/dCm59/2/)

But if I try to make it work for collections of elements (adding each), it removes the original:

$.prototype.cloneDumpingEvents = function () {
    return this.each(function() {
        $(this).clone();
    });
};

(Or, see it in action: http://jsfiddle.net/Shawn/dCm59/3/)

Why does the second version remove the original?

Was it helpful?

Solution

Because you're returning the original instead of the clone. Use this instead:

$.fn.cloneDumpingEvents = function () {

    var collection = $();

    this.each(function() {
        collection = collection.add( $(this).clone() );
    });

    return collection;
};

Here's your fiddle: http://jsfiddle.net/dCm59/4/


As pointed out by @FabrícioMatté in the comments, .map is way shorter:

$.fn.cloneDumpingEvents = function () {
    return this.map(function() {
        return $.clone(this);
    });
};

Here's your fiddle again: http://jsfiddle.net/dCm59/7/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top