Remove items from the DOM and add them to where they were

I have a modal window. I want to remove some elements from the page when the modal opens and add them back to the right, where they were after the mod was closed. I do not want to show: no, because it only hides them, I need them to be removed from the page. So I have a little jQuery to remove and add them back after the timer just for testing ...

UPDATED: with these code additions, it now grabs the element earlier, and then adds it back after the same element. The problem is, what if this item was also deleted? Then he will not add back! Also, won't javascript event handlers be lost? I am developing a plugin, so it should interfere with the site as little as possible, but the three elements have an error in Safari that cannot be circumvented.

Any ideas on how I can temporarily remove 3D elements without disturbing the site of people too much?

$3delements = $('*').filter(function(){return $(this).css('-webkit-transform-style') == 'preserve-3d'}); $3delementsposition = $3delements.prev() //On modal open $3delements.remove(); //On modal close $3delementsposition.after($3delements); 

The problem is that this requires you to specify a specific place in the DOM so that they can return. I would like the elements to return to where they were. How can I make sure that the elements do not change / move / do not lose information on .remove on .append.

+6
source share
3 answers
  • Use .detach() and .append() to remove and reconnect items, it will support all your events and data.

  • If you add items in the reverse order that you deleted them, they should all be back in place


unverified code


 var elems3d = $(...); var elemsRemoved = []; // removing elems3d.each(function(i,o) { var elem = $(o); elemsRemoved.push({ loc: elem.prev(), obj: elem.detach() }); }); // adding back while (elemsRemoved.length) { var elem = elemsRemoved.pop(); elem.loc.after(elem.obj); } 
+8
source

Instead of deleting elements, replace them with placeholder elements (using replaceWith ), then replace the placeholders with the original content if necessary. Something like the following:

 $3delements = $('*').filter(function(){return $(this).css('-webkit-transform-style') == 'preserve-3d'}); var originals = []; $3delements.each(function() { // Clone original, keeping event handlers and any children elements originals.push($(this).clone(true)); // Create placeholder for original content $(this).replaceWith('<div id="original_' + originals.length + '"></div>'); }); /// /// Do something asynchronous /// // Replace placeholders with original content for (var i in originals) { $('#original_' + (i + 1)).replaceWith(originals[i]); } 

See clone and replaceWith in jQuery docs for more information.

+5
source

I created a violin. Let me know if this fulfills your requirement.

http://jsfiddle.net/mNsfL/12/

-4
source

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


All Articles