JQuery: Looking for a cloned child in a cloned parent?

Let's say I have this jQuery extension method:

$.fn.foobar = function() {
    var clone = this.parent().clone();
};

After I got it clone, how can I find a cloned child that matches this?

Will this work?

$.fn.foobar = function() {
    var clone = this.parent().clone();
    var cloneOfThis = clone.find(this);
};

Or that?

$.fn.foobar = function() {
    var clone = this.parent().clone();
    var self = this;
    var cloneOfThis;
    clone.children().each(function() {
        var $this = $(this);
        if ($this === self) {
            cloneOfThis = $this;
        }
    });
};
+3
source share
3 answers

You can try giving it a unique class that you can use to refer to the correct element.

$.fn.foobar = function() {
      // Add a class to "this", then clone its parent
    var clonedParent = this.addClass("someUniqueClass").parent().clone();
      // Reference the new clone of "this" inside the cloned parent,
      //   then remove the class
    var cloneOfThis = clonedParent.find(".someUniqueClass").removeClass("someUniqueClass");
      // Remove the class from the original
    this.removeClass("someUniqueClass");
};
+3
source

, this , , . , , , , , " ", , HTML-, ?

, , ... -, :)

+1

Taking patrick dw, answer a little further and include the Felix King comment, I would suggest the following:

$.fn.foobar = function() {
    return $(this).each(function() {
        // Add a class to "this", then clone its parent
        var clonedParent = $(this).addClass("someUniqueClass").parent().clone();

        // Reference the new clone of "this" inside the cloned parent
        var cloneOfThis = clonedParent.find(".someUniqueClass");

        //remove the unique class to preserve the original state (other than the clone which is now present)
        $('.someUniqueClass').add(cloneOfThis).removeClass('someUniqueClass');
    });
};
0
source

Source: https://habr.com/ru/post/1762961/


All Articles