Framework & Library/JQeury

[JQuery] Mainipulation method

gangintheremark 2023. 7. 14. 14:53
728x90

Jquery의 Manipulation 메소드를 이용하여 DOM을 추가하거나 수정, 삭제, 복사하는 등의 처리를 하여 동적인 HTML 화면을 손쉽게 구현할 수 있다.

메소드 예시 설명
💡 .append() $("selector").append(html) 선택된 요소의 자식으로 들어가 뒤에 추가
💡 .prepend() $("selector").prepend(html) 선택된 요소의 자식으로 들어가 앞에 추가
💡 .before() $("selector").before(html) 선택된 요소의 형제로 들어가 앞에 추가
💡 .after() $("selector").after(html) 선택된 요소의 형제로 들어가 뒤에 추가
💡 .replaceWith() $("selector").replaceWith(html) 선택된 요소를 제거하고 지정된 값으로 치환
💡 .remove() $("selector").remove() 선택된 요소 포함 제거
💡 .empty() $("selector").empty() 선택된 요소인 하위요소 삭제
💡 .clone $("selector").clone() 선택된 요소를 포함한 모든 하위요소 복제
$("selector").clone(true) 복제 시 이벤트 핸들러까지 복제할지 true/false 로 설정
<head>
  <script>
    $(document).ready(function () {
      $("#append").on("click", function () { // 자식으로 들어가 뒤에 추가
        $("#result").append("<h1>홍길동</h1>");
      });
      $("#prepend").on("click", function () {
        $("#result").prepend("<h1>홍길동</h1>"); // 자식으로 들어가 앞에 추가
      });

      $("#before").on("click", function () {
        $("#result").before("<h1>홍길동</h1>"); // 형제로 들어가 앞에 추가
      });
      $("#after").on("click", function () {
        $("#result").after("<h1>홍길동</h1>"); // 형제로 들어가 뒤에 추가
      });
      $("#replaceWith").on("click", function () {
        // id="result" 인 자신이 삭제되고 지정된 값으로 치환된다
        $("#result").replaceWith("<h1>홍길동</h1>");
      });

      $("#remove").on("click", function () {
        // id="result" 인 자신이 삭제
        $("#result").remove();
      });

      $("#empty").on("click", function () {
        // id="result" 인 하위 요소 삭제
        $("#result").empty();
      });
    });
  </script>
</head>
<body>
  <div id="result">
    <p>Hello</p>
  </div>
  <button id="append">append</button><br>
  <button id="prepend">prepend</button><br>
  <button id="before">before</button><br>
  <button id="after">after</button><br>
  <button id="replaceWith">replaceWith</button><br>
  <button id="remove">remove</button><br>
  <button id="empty">empty</button><br>
</body>

728x90