본문 바로가기
프로그래밍/jQuery

jQuery API 정복 - 요소 바꾸기, replaceWith()

by zoo10 2011. 11. 22.

.replaceWith()

원문 링크 http://api.jquery.com/replaceWith/

.replaceWith( newContent )Returns : jQuery

개요 : 조건에 맞는 요소들을 newContent로 대체합니다.

  • .replaceWith( newContent )
  • newContent 대체될 컨텐츠. HTML string, DOM element, jQuery object.
  • .replaceWith( function )
  • function 대체될 컨텐츠를 반환하는 함수.

.replaceWith() 함수는 새로운 컨텐츠로 바꾸고 대체된 요소는 DOM에서 제거합니다. DOM 구조를 예로 보시죠.

<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>

second inner <div> 를 HTML로 바꿔보죠.

$('div.second').replaceWith('<h2>New heading</h2>');

이 결과는요.

<div class="container">
  <div class="inner first">Hello</div>
  <h2>New heading</h2>
  <div class="inner third">Goodbye</div>
</div>

inner 가 들어간 모든 <div> 요소들도 바꿔보죠.

$('div.inner').replaceWith('<h2>New heading</h2>');

모두 바뀐 결과를 볼 수 있습니다.

<div class="container">
  <h2>New heading</h2>
  <h2>New heading</h2>
  <h2>New heading</h2>
</div>

기존의 요소를 선택해서 바꿔줄 수도 있습니다.

$('div.third').replaceWith($('.first'));

DOM 이 아래와 같이 바뀝니다.

<div class="container">
  <div class="inner second">And</div>
  <div class="inner first">Hello</div>
</div>

위 예를 보면, 선택된 요소는 이전 위치에서 옮겨져 타겟을 대체한다는 것을 볼 수 있습니다. 기존 위치에 남아 복사되는 것이 아닙니다.

.replaceWith() 함수는 대부분의 jQuery 함수들에서와 마찬가지로 다른 jQuery의 함수들과 체인형태로 사용할 수 있습니다. 이때 반환된 jQuery 객체는 original 입니다. 다시말해 이 객체는 DOM에서 제거된 요소라는 것입니다. 새로 대체되어 문서에 추가된 요소를 말하는 것이 아닙니다. 음. 체인 형태로 함수를 이어서 사용하면 replaceWith() 함수는 해당 함수로 인해 제거된 객체를 반환해서 다음 함수로 전달해 준다는 얘기인것 같습니다.

jQuery 1.4에서의 .replaceWith() 함수는 DOM 노드들을 분리하는 기능도 할수 있게 되었습니다. 다음 코드처럼 .replaceWith() 문단을 포함시켜 단락을 만들어 내는 것처럼 말입니다.(응? 갑자기 군대용어를 ;;;)

$("<div/>").replaceWith("<p></p>");

.replaceWith()는 인자로 함수를 가질 수도 있습니다.

$('div.container').replaceWith(function() {
  return $(this).contents();
});

이 함수는 HTML string, DOM element, jQuery object 등을 반환해야 합니다.

예 제  
클릭해서 버튼을 div를 바꿔볼까요.

<!DOCTYPE html>
<html>
<head>
  <style>
  button { display:block; margin:3px; color:red; width:200px; }
  div { color:red; border:2px solid blue; width:200px;
      margin:3px; text-align:center; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<button>First</button>
<button>Second</button>
<button>Third</button>

<script>
$("button").click(function () {
  $(this).replaceWith( "<div>" + $(this).text() + "</div>" );
});
</script>

</body>
</html>

미리보기

클릭하면 테두리가 있는 div로 바뀌네요. 와우~

 

예 제  
모든 문단의 텍스트를 굵은 글씨체로 바꿉니다.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<p>Hello</p>
<p>cruel</p>
<p>World</p>

<script>
$("p").replaceWith( "<b>Paragraph. </b>" );
</script>

</body>
</html>

미리보기

요건 replaceAll()에서도 나왔던거 같은데. 모두 굵은 글씨의 Paragraph로 바꼈네요.

 

예 제  
On click, replace each paragraph with a div that is already in the DOM and selected with the $() function. Notice it doesn't clone the object but rather moves it to replace the paragraph.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { border:2px solid blue; color:red; margin:3px; }
  p { border:2px solid red; color:blue; margin:3px; cursor:pointer; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>

  <div>Replaced!</div>

<script>
$("p").click(function () {
  $(this).replaceWith( $("div") );
});
</script>

</body>
</html>

미리보기

빨간 테두리의 p를 클릭하면 파란 테두리의 div로 대체됩니다. 이동되요.

 

예 제  
버튼을 클릭하면 div의 클래스를 바꿔주고 어떤 클래스 명이었는지 확인해 보아요.

<!DOCTYPE html>
<html>
<head>
  <style> 
  .container { background-color: #991; }
  .inner { color: #911; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<p>
  <button>Replace!</button>
</p>
<div class="container">
  <div class="inner">Scooby</div>
  <div class="inner">Dooby</div>
  <div class="inner">Doo</div>
</div>

<script>
$('button').bind("click", function() {
  var $container = $("div.container").replaceWith(function() {
    return $(this).contents();
  });

  $("p").append( $container.attr("class") );
});
</script>

</body>
</html>

미리보기

이건 그냥 함수도 인자로 쓸수 있다 정도의 예제라고나 할까요. :)

 

그럼 즐프하세요.

※ 본 예제는 http://www.jquery.com 에 있는 내용임을 밝힙니다.