Is there any solution for deleting an item, if it exists, and creating, if not? Similar to toggleClass or toggleFade. These two methods are not suitable. hide the element visually, but at the DOM level it is preserved.
- No, there is no such thing from the box, but you can always write it yourself - Grundy
|
1 answer
Hiding an item through a class is a reversible and switchable process, and complete deletion is irreversible.
However, you can save your element in js in order to insert it again into the DOM in the future. A suitable example is in the documentation for the jquery detach()
method ( https://api.jquery.com/detach/ ), it will work for you.
var p; $( "button" ).click(function() { if ( p ) { p.appendTo( "body" ); p = null; } else { p = $( "p" ).detach(); } });
Also, instead of detach()
you can use the remove()
method, which will also remove the element from the DOM, but with all event handlers attached to it.
- and the complete removal is not entirely irreversible :-) - Grundy
- @Grundy, that is, the element removed from the DOM still remains somewhere? - Vitaly Emelyantsev
- oneThe only difference between detach and remove is that when using remove, hung event handlers are removed - Grundy
- Actually, this is exactly the first line in the help: _The .detach () method is the same as .remove () , except that .detach () keeps all _ - Grundy
- oneyeah, I wrote about it in the second comment :-) - Grundy
|