ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • jQuery append, prepend, after, before
    Web/jQuery 2018. 9. 5. 10:58

    특정 태그를 기준으로 Element를 첨부하고 싶을 때 Selector와 다음 함수들을 사용한다. 코드 먼저 보도록 하자.

    ※모든 예제는 아톰(atom)으로 작성했고, 오페라 브라우저를 통해 확인했다. html 문서 작업이 굉장히 편하기 때문에 사용을 권하고, 브라우저는 크롬이나 오페라를 권장한다. 인터넷 익스플로러에서는 같은 결과가 나오지 않는 경우가 굉장히 많을 것이다. ( 브라우저들의 DOM 작성 방법이 표준화되지 않았기 때문)




    <!DOCTYPE html>
    <html>
      <head>
        <link rel="stylesheet" type="text/css" href="./layout.css" />
        <title>Vacation Packages</title>
        <script type="text/javascript" src="./jquery-3.1.1.min.js"></script>
        <script type="text/javascript">
        // 태그들 객체화 시키는 작업이 끝나면 jQuery 실행 콜백 function
          $(document).ready(function(){
    
            var price = $("<p id='price'>from $399.99</p>"); // 매개변수에 해당하는 Element가 만들어진다.
    
            $(".vacation").before(price);
            //$(".vacation").after(price);
            //$(".vacation").prepend(price);
            //$(".vacation").append(price);
    
            // 다음 두가지는 같은 위치 표기할 수 있다.
            //$(".comments").before(price);
            //$(".vacation > p").after(price);
          });
        </script>
      </head>
      <body>
        <fieldset>
          <legend>Vacations</legend>
          <h1>Vacation Packages</h1>
          <h3>jQuery Travels</h3>
          <ul>
            <li class='vacation'>
              <h2>Hawaiian Vacation</h2>
              <p>Comments on this deal:</p>
              <ul class="comments">
                <li>"Amazing Deal!"</li>
                <li>"Can't wait to take this trip!"</li>
              </ul>
              <button>GET PRICE</button>
            </li>
          </ul>
          <p class="call">Call us at 1-555-jquery-air to make a reservation today!</p>
        </fieldset>
      </body>
    </html>
    
    

    price 에 p태그를 Element화 시켜 저장한다.
    이후 $ 연산자를 통해 vacation 클래스를 찾은 후 before함수의 매개변수에 price를 넣어 vacation 클래스 앞에 붙이도록 한다. 그 결과는

    1) before 결과
    다음과 같이 vacation 태그 바로 전에 출력된다.
    코드의 주석들을 바꿔가며 after, prehend, append의 결과를 확인한다.

    2) after 결과

    3) prehend 결과

    4) append 결과

    vacation 클래스는 html 을 확인해보면 파악 가능하겠지만 p태그가 붙은 회검색 박스 부분이다. 결과들이 출력되는 것을 보아

    before : 셀렉터 태그 이전에 추가
    after : 셀렉터 태그 이후에 추가
    prehend : 셀렉터 태그 안 가장 처음에 추가
    append : 셀렉터 태그 안 가장 마지막 요소에 추가

    됨을 파악할 수 있다.

    이를 이해했다면 p태그의 위치를 적절히 조절 가능하다. Comments on this deal 다음에 나오고 싶게 하고 싶다면

    1) $(".comments").before(price);
    2) $(".vacation > p").after(price);
    다음과 같은 방법들을 통해 위치시킬 수 있는 것이다.




Designed by Tistory.