Java Script/JQuery

jQuery 요소 대체하기 (replaceAll/replaceWith)

서으이 2020. 11. 1. 17:53
728x90
반응형

replaceAll

. replaceAll() 메서드는 선택한 요소를 지정된 요소로 대체합니다.
이 메소드는 인수로 선택자나 제이쿼리 객체, HTML DOM 요소, 배열 등을 전달받을 수 있습니다.

  target 유형 설명
.replaceAll (대상) 선택기 또는 jQuery 또는 배열 또는 요소 대체 할 요소를 나타내는 선택기 문자열, jQuery 
객체, DOM 요소 또는 요소 배열입니다.

 

 .replaceAll()방법은 후술 할. replaceWith()와유사합니다.

하지만 소스와 대상이 반대입니다.

다음 예문을 참고 바랍니다.

 

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

요소를 만든 다음 다른 요소를이 요소로 바꿀 수 있습니다.

해당 jQuery .replaceAll() 문법을 통해 요소가 모두 교체됩니다.

 

$( "<h2>New heading</h2>" ).replaceAll( ".inner" );
 
//결과
<div class="container">
  <h2>New heading</h2>
  <h2>New heading</h2>
  <h2>New heading</h2>
</div>
cs

 

모든 단락을 굵은 단어로 바꾸는 예제입니다.

 

<!doctype html>
<head>
  <meta charset="utf-8">
  <title>replaceAll demo</title>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<p>동해물과 백두산이</p>
<p>마르고 닳도록</p>
<p>하느님이 보우하사</p>
<p>우리나라 만세</p>
 
<script>
$( "<b> 굵은 글씨  </b>" ).replaceAll( "p" );
</script>
 
</body>
</html>
cs

 

replaceWith

. replaceWith() 메서드는 선택한 요소를 지정된 요소로 대체합니다.
이 메소드는 인수로 HTML 코드 형식의 문자열이나 제이쿼리 객체, HTML DOM 요소, 배열 등을 전달받을 수 있습니다.
또한, 선택한 요소를 대체할 수 있는 콘텐츠를 반환하는 함수를 인수로 전달받을 수도 있습니다.
. replaceWith() 메서드의 동작은. replaceAll() 메서드와 비슷하지만, 소스(source)와 타깃(target)의 위치가 서로 반대입니다.
또한,. replaceWith() 메서드는 지정된 요소로 대체되어 제거된 기존 요소를 반환합니다.

 

$(바꾸고 싶은 요소).replaceWith(바뀌게 될 요소);
cs

 

아래 코드는 아이템 대체 버튼을 클릭하면 li id가 "firstItem"로 바뀌는 예문입니다.

 

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>jQuery Element Replace</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script>
        $(function() {
            $("button").on("click"function() {
                // class가 "item"인 모든 요소를 id가 "firstItme"인 요소로 대체함.
                $(".item").replaceWith($("#firstItem"));
            });
        });
    </script>
</head>
 
<body>
 
    <h1>.replaceWith() 메소드</h1>
    <ul>
        <li class="item" id="firstItem">첫 번째 아이템이에요!</li>
        <li class="item" id="secondItem">두 번째 아이템이에요!</li>
        <li class="item" id="thirdItem">세 번째 아이템이에요!</li>
    </ul>
    <button>아이템 대체</button>
    
</body>
 
</html>
cs

 

728x90
반응형