온 코딩

[jQuery] .append(), .empty(), .wrap(), insertAfter(), .before(), .colon(), .replaceWith(), .remove() , .css() 본문

복습 ARCHIVE/java script

[jQuery] .append(), .empty(), .wrap(), insertAfter(), .before(), .colon(), .replaceWith(), .remove() , .css()

SummerON 2021. 6. 8. 08:40

.empty(태그 비우기) <-> .append(태그 안에 내용 추가하기)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
    <title>DOM 요소 생성 후 원하는 요소에 추가</title>

    <style type="text/css">
        .Yellow{ background-color: Yellow }
        .Green{ background-color: Green }
    </style>

    <script src="jquery-1.6.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {

            //[1] 태그안의 내용 초기화
            $('#lblDisplay').empty(); // <b>태그 초기화 시킴

            //[2] 동적으로 태그 추가
            var strHtml = $("<a href='#'>닷넷코리아</a><hr />");
            $('#lblDisplay').append(strHtml);

            //[3] 버튼 클릭시 테이블 생성
            $('#btnCreate').click(function() {

                $('#lblTable').empty(); // 클리어 : 이 부분을 생략했을 경우.. 버튼을 클릭할 때마다 

                var row = $('#row').val();
                var col = $('#col').val();
                var strTable = "<table border='1'>";

                for (var i = 0; i < row; i++) {   // 행반복 <tr>
                    strTable += "<tr>";

                    for (var j = 0; j < col; j++) {  // 열반복  <td>
                        strTable += "<td>" + (i + 1) + "행, " + (j + 1) + "열" + "</td>";
                    }

                    strTable += "</tr>";
                }

                strTable += "</table>";

                $('#lblTable').append(strTable);
                
                $('tr:odd').addClass('Yellow');
                $('tr:even').addClass('Green');
                
                $('td:odd').addClass('Yellow');
                $('td:even').addClass('Green');
            });
        });
    </script>

</head>

<body>

	<!--동적으로 태그 추가 -->
	<span id="lblDisplay"><b>여기에 태그 추가</b></span>
	
	<!--동적으로 테이블 추가 -->
	<input type="text" id="row" />행
	<input type="text" id="col" />열
	<input type="button" id="btnCreate" value="테이블 동적 생성" />
	
	<div id="lblTable">     </div>

</body>

</html>

.insertAfter() - ()뒤에 삽입 / .before() - () 내용을 삽입 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
    <title>DOM 요소의 앞/뒤에 요소추가</title>

    <style type="text/css">
        .Chapter { background-color:Silver; }
        .Content { height:100px; border:1px solid red; }
    </style>

    <script src="jquery-1.6.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {

            //[1] 내용 뒤에 구분선(<hr />) 삽입
            $('<hr />').insertAfter(".Content");
			// class 속성값이 .Content 인 요소의 뒤에 <hr /> 태그 삽입
			
            //[2] TOP 링크를 Chapter 앞에 추가
            $('p.Chapter:gt(0)').before("<a href='#'>TOP</a>");
			// <p>태그 중 class 속성값이 Chapter 인 요소들 중 인덱스 번호가 0보다 큰 요소만
			// 그 앞에 <a href='#'>TOP</a> 요소를 추가..
			
			// p : <p>태그 중
			// .Chapter : class 속성값이 Chapter 인 요소들 중
			// :gt(0) : 인덱스 번호가 0보다 큰 요소
			// 앞에 : .before()
			// <a href='#'>TOP</a> 요소를 추가

        });
    </script>

</head>

<body>

    <p class="Chapter">1 장</p>
    <div class="Content">
    	내용1...
    </div>

    <p class="Chapter">2 장</p>
    <div class="Content">
    	내용2...
    </div>

    <p class="Chapter">3 장</p>
    <div class="Content">
    	내용3...
    </div>

</body>

</html> 

.css()

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
    <title>특정 용어에 대해서 번호 붙이기</title>

    <style type="text/css">
        .Chapter { background-color:Silver; }
        .Content { height:100px; border:1px solid red; }
    </style>

    <script src="jquery-1.6.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {

            //[1] term CSS 클래스에 배경색 적용
            $('.term')
            .not(":odd").css("background-Color", "Yellow")
            .end()
            .filter(":odd").css("background-color", "LightBlue");

            //[2] 각각의 주석/용어 뒤에 번호 붙이기
            $('.term').each(function(i) { $(this).append("<sub>" + (i + 1) + "</sub>"); });
            
            // <span class="term">jQuery<sup>1</sup></span>
            // <span class="term">JavaScript<sup>2</sup></span>
            // <span class="term">HTML<sup>3</sup></span>
            // <span class="term">Ajax<sup>4</sup></span>

        });
    </script>

</head>

<body>

<h3>jQuery is a new kind of JavaScript Library</h3>
<div>
    <span class="term">jQuery</span> is a fast and concise <span class="term">JavaScript</span> Library 
    that simplifies <span class="term">HTML</span> document traversing, 
    event handling, animating, and <span class="term">Ajax</span> interactions 
    for rapid web development. 
    jQuery is designed to change the way that you write JavaScript.
</div>

</body>

</html> 

.wrap()

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
    <title>검색된 요소를 특정 태그로 감싸기(wrap)</title>

    <script src="jquery-1.6.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {

            //[1] <h3>...</h3>을 <u>태그로 묶자
            $('h3').wrap("<u></u>");

            //[2] 모든 A 태그를 <li>으로 묶자.
            //[a] 첫번째 링크앞에 동적으로 <ol> 태그 삽입
            $('<ol type="1" id="community"></ol>').insertAfter('a:eq(0)');

            //[b] 모든 링크를 <li>로 감싸고 이를 <ol> 태그로 추가
            $('a').each(function() {
                $(this).appendTo('#community').wrap('<li></li>');
            }); 

        });

    </script>

</head>

<body>

    <h3>.NET 기술 관련 커뮤니티</h3>
    <a href="http://www.asp.net/">ASP.NET</a>
    <a href="http://www.silverlight.net/">Silverlight</a>
    <a href="http://www.windowsclient.net/">WPF</a>
    <a href="http://www.dotnetkorea.com/">.NET All(?)</a>

</body>

</html> 

.prependTo() = insertBefore() - ()를 앞에 추가 / .apeendTo() <-> .append()

.clone()

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
    <title>검색된 요소를 복사하기</title>

    <style type="text/css">
        #menu { background-color:Blue; color:White; }
        #submenu { background-color:Silver; }
        #content { height:100px; }
    </style>

    <script src="jquery-1.6.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {

            //[!] 상단 메뉴를 복사(Clone)해서 하단 메뉴에 추가(Append)
            $('#menu').clone().insertBefore('#submenu');
            $('#content').clone().prependTo('#submenu');

//             // 원래 하단 메뉴가 있는 위치
//             $('#menu').clone().insertAfter('#submenu');
//             $('#menu').clone().appendTo('#submenu');

        });
    </script>

</head>

<body>
	<div id="menu">
	HOME About
	</div>
	
	<div id="content">
	상단 메뉴를 아래 하단메뉴에 복사
	</div>
	
	<div id="submenu">
	여기는 하단메뉴 들어오는 곳
	</div>

</body>

</html> 

.replaceWith()

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
    <title>검색된 요소를 변경하기</title>

    <style type="text/css">
        button { display:block; margin:3px; color:Red; width:200px; }
        div { color:Red; border:2px solid blue; width:200px;
              margin:3px; text-align:center; }
    </style>

    <script src="jquery-1.6.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {

            //모든 버튼 요소를 클릭시
            $("button").click(function() {

                //나 자신(버튼)을 <div> 태그로 변경하자.
                $(this).replaceWith("<div>" + $(this).text() + "</div>");

               // $(this) : click 이벤트를 발생시킨 요소
               // .replaceWith("~~") : 요소 변경.. (내부 요소변경이 아닌, 자기 자신 요소 변경!!!)
               // $(this).text()  => First
               // 즉, <button>First</button>   => <div>First</div>
            });
        });
    </script>

</head>

<body>

    <button>First</button>
    <button>Second</button>
    <button>Third</button>

</body>

</html> 


.remove() - 삭제 / .empty() - 내용 비우기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
    <title>검색된 요소를 완전 제거</title>

    <style type="text/css">
        div { background-color:Yellow; }
    </style>

    <script src="jquery-1.6.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {

            //[1] 내용 지우기
            $('#btnEmpty').click(function() {
                $('div').empty();
                $('div').append("<b>hi</b>"); // div에 추가 가능
            });

            //[2] 요소 없애기
            $('#btnRemove').click(function() {
                $('div').remove();
                $('div').append("<b>hi</b>"); // div 없다.
            });

        });
    </script>

</head>

<body>

    <div>
        <p>jQuery</p>
        <p>Ajax</p>
    </div>

    <input type="button" id="btnEmpty" value="위 영역 비우기" />
    <input type="button" id="btnRemove" value="위 영역 삭제" />

</body>

</html>
Comments