목차

jQuery - Add Elements

  • description : jQuery - Add Elements
  • author : 오션
  • email : shlim@repia.com
  • lastupdate : 2021-04-16


jQuery를 사용하면 새로운 요소/콘텐츠를 쉽게 추가할 수 있습니다.

Add New HTML Content

새 콘텐츠를 추가하는 데 사용되는 네 가지 jQuery 메서드를 살펴 보겠습니다.


jQuery append() Methods

jQuery append() 메서드는 선택한 HTML 요소의 끝 부분에 콘텐츠를 삽입합니다.

예제

    $(document).ready(function () {
      $("#btn1").click(function () {
        $("p").append("<b>Appended text</b>.")
      });
 
      $("#btn2").click(function () {
        $("ol").append("<li>Appended item</li>");
      });
    });


jQuery prepend() Method

jQuery prepend() 메서드는 선택한 HTML 요소의 시작 부분에 콘텐츠를 삽입합니다.

예제

    $(document).ready(function () {
      $("#btn1").click(function () {
        $("p").prepend("<b>Prepended text</b>.");
      });
 
      $("#btn2").click(function () {
        $("ol").prepend("<li>Prepended item</li>");
      });
    });

Add several New Elements With append() and prepend()

위의 두 예제에서, 선택한 HTML 요소의 시작/끝 부분에 일부 텍스트/HTML만 삽입했습니다.

그러나 append()prepend() 메서드 두 개 모두, 무한한 수의 새 요소를 매개 변수로 사용할 수 있습니다.
위의 예에서 한 것처럼 텍스트/HTML로, jQuery 또는 JavaScript 코드 그리고 DOM 요소를 사용하여,
새로운 요소들을 생성할 수 있습니다.

다음 예에서는 몇 가지 새로운 요소들을 만듭니다. 요소들은 text/HTML, jQuery 및 JavaScript/DOM으로 생성됩니다.
그런 다음 append() 메서드를 사용하여 텍스트에 새 요소를 추가합니다.
(prepend()에서도 실행될 것입니다).

예제

    function appendText() {
      var txt1 = "<p>사랑해!</p>";                   // Create text with HTML
      var txt2 = $("<p></p>").text("I love you.");  // Create text with jQuery
      var txt3 = document.createElement("p");
      txt3.innerHTML = "Je t'aime.";                // Create text with DOM
      $("body").append(txt1, txt2, txt3);           // Append new elements
    }

jQuery after() and before() Methods

jQuery after() 메서드는 선택한 HTML 요소들 뒤(AFTER)에 콘텐츠를 삽입합니다.

jQuery before() 메서드는 선택한 HTML 요소들 앞(BEFORE)에 콘텐츠를 삽입합니다.

예제

    $(document).ready(function () {
      $("#btn1").click(function () {
        $("img").before("<b>Before</b>");
      });
      $("#btn2").click(function () {
        $("img").after("<i>After</i>");
      });
    });

Add Several New Elements With after() and before()

또한 after()before() 메서드 두 개 모두 무한한 수의 새 요소들을 매개 변수로 사용할 수 있습니다.
위의 예제에서 한 것처럼 text/HTML, jQuery 또는 JavaScript 코드 그리고 DOM 요소를 사용하여,
새로운 요소들을 생성할 수 있습니다.

다음 예제에서는, 몇 가지 새로운 요소들을 만듭니다.
요소들은 text/HTML, jQuery 및 JavaScript/DOM으로 생성됩니다.
그런 다음 after() 메서드를 사용하여 새 요소들을 텍스트에 삽입합니다
(이것은 before()에서도 실행될 것입니다).

예제

    function afterText() {
      var txt1 = "<b>We </b>";                 // Create element with HTML
      var txt2 = $("<i></i>").text("like ");  // Create with jQuery
      var txt3 = document.createElement("b"); // Create with DOM
      txt3.innerHTML = "jQuery!!!!!";
      $("img").after(txt1, txt2, txt3);       // Insert new elements after img
    }

jQuery HTML Reference

모든 jQuery HTML 메서드에 대한 전체 개요를 보려면, jQuery HTML/CSS Reference로 이동하십시오.