jQuery / Method / .detach() - 선택한 요소를 문서에서 제거하고 저장하는 메서드
.detach()
.detach()는 선택한 요소를 문서에서 제거합니다. 제거한다는 면에서는 .remove()와 같으나, .detach()는 제거한 요소를 저장하여 다시 사용할 수 있습니다.
문법
.detach( [selector ] )
예를 들어
var jb = $( 'h1' ).detach();
는 h1 요소를 문서에서 제거하고 변수 jb에 저장합니다.
예제
Cut 버튼을 클릭하면 Dolor를 잘라내고, Paste 버튼을 클릭하면 Ipsum 위에 붙여넣습니다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> <script> jQuery( document ).ready( function() { var jbDetach; $( '#cut' ).click( function() { jbDetach = $( '.b' ).detach(); } ); $( '#paste' ).click( function() { $( '.a' ).before( jbDetach ); } ); } ); </script> </head> <body> <h1>Lorem</h1> <h2 class="a">Ipsum</h2> <h2 class="b">Dolor</h3> <button id="cut">Cut</button> <button id="paste">Paste</button> </body> </html>