선택한 요소를 다른 것으로 바꾸는 방법 - .replaceWith()

replaceWith는 선택한 요소를 다른 것으로 바꿉니다.
1 min read

.replaceWith()

.replaceWith()는 선택한 요소를 다른 것으로 바꿉니다.

 

기본형

.replaceWith( newContent )

newContent에는 특정 요소가 들어갈 수 있습니다.

예를 들어 h1 요소를 abc로 바꾸고 싶다면 다음과 같이 합니다.

$( 'h1' ).replaceWith( 'abc' );

h1 요소의 내용 뿐 아니라 h1 태그까지 지우고 바꾼다는 것에 주의합니다.

예를 들어

$( 'h1' ).replaceWith( $( 'p.a' ) );

는 h1 요소를 클래스 값이 a인 p 요소로 바꿉니다.

 

예제 1

버튼을 클릭하면 <h1> 요소를 <p>Ipsum</p>로 바꿉니다.

<h1>Lorem</h1>
<button>Replace</button>
$( document ).ready( function() {
  $( 'button' ).click( function() {
    $( 'h1' ).replaceWith( '<p>Ipsum</p>' );
  });
});

 

예제 2

버튼을 클릭하면 <h1> 요소를 abc를 클래스 값으로 가지는 요소로 바꿉니다.

<h1>Lorem</h1>
<p>Ipsum</p>
<p class="abc">Dolor</p>
<button>Replace</button>
$( document ).ready( function() {
  $( 'button' ).click( function() {
    $( 'h1' ).replaceWith( $( '.abc' ) );
  });
});

You may like these posts

Post a Comment