SeouliteLab

jQuery의 .replaceWith() 메소드: 요소 교체하기 본문

프로그래밍

jQuery의 .replaceWith() 메소드: 요소 교체하기

Seoulite Lab 2024. 4. 8. 08:04

다양한 .replaceWith() 메소드 예제

jQuery의 .replaceWith() 메소드는 선택한 요소를 다른 요소로 교체합니다. 이를 통해 웹 페이지의 요소를 동적으로 변경할 수 있습니다. 아래 예제들을 통해 이 메소드의 활용법을 살펴보겠습니다.

예제 1: 기본적인 사용법

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .replaceWith() 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $(".old").replaceWith("<div class='new'>새로운 요소</div>");
    });
  </script>
</head>
<body>

<div class="old">교체될 요소</div>

<!-- 출력 결과: (".old" 클래스를 가진 요소가 "<div class='new'>새로운 요소</div>"로 교체됨) -->

</body>
</html>

예제 2: 여러 요소에 대한 교체

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .replaceWith() 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("span").replaceWith("<div>새로운 요소</div>");
    });
  </script>
</head>
<body>

<span>교체될 요소 1</span>
<span>교체될 요소 2</span>

<!-- 출력 결과: (모든 <span> 요소가 "<div>새로운 요소</div>"로 교체됨) -->

</body>
</html>

예제 3: 교체된 요소에 대한 이벤트 처리

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .replaceWith() 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $(".old").replaceWith("<button class='new'>새로운 버튼</button>");
      $(".new").click(function(){
        alert("새로운 버튼이 클릭되었습니다!");
      });
    });
  </script>
</head>
<body>

<div class="old">클릭하여 교체될 요소</div>

<!-- 출력 결과: (".old" 클래스를 가진 요소가 "<button class='new'>새로운 버튼</button>"으로 교체되고, 클릭 이벤트가 추가됨) -->

</body>
</html>

예제 4: 교체된 요소에 대한 스타일 적용

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .replaceWith() 예제</title>
  <style>
    .highlight {
      background-color: yellow;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      var newElement = $("<div>새로운 강조 요소</div>").addClass("highlight");
      $(".old").replaceWith(newElement);
    });
  </script>
</head>
<body>

<div class="old">교체될 강조 요소</div>

<!-- 출력 결과: (".old" 클래스를 가진 요소가 "새로운 강조 요소"로 교체되고, 강조 스타일이 적용됨) -->

</body>
</html>

예제 5: 제거된 요소에 대한 다른 작업 수행

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .replaceWith() 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      var removedElement = $(".old").replaceWith("<div>새로운 요소</div>");
      removedElement.css("color", "red");
    });
  </script>
</head>
<body>

<div class="old">교체될 요소</div>

<!-- 출력 결과: (".old" 클래스를 가진 요소가 "새로운 요소"로 교체되고, 제거된 요소에 빨간색 글자색이 적용됨) -->

</body>
</html>

.replaceWith() 메소드를 사용하면 선택한 요소를 다른 요소로 간편하게 교체할 수 있습니다. 이를 통해 웹 페이지의 동적인 변경이 가능하며, 위 예제들을 통해 다양한 활용법을 익혀보세요.