jQuery

jQuery - .detach()

행복하게사는게꿈 2020. 6. 23. 15:45

.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>