티스토리 뷰

사실 jQuery를 사용하는 가장 큰 이유 중 하나가 바로 동적으로 어떤 요소를 추가하거나 삭제하기 편리하다는 점일 것이다. 

이번 포스팅에서는 세상 편리하게 동적으로 html 요소를 추가하는 몇 가지 방법을 작성해보려고 한다.

바로 확인해보자.


1. append: 동적으로 html 태그를 추가하는 함수

 1) 테이블 동적 추가

<!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() {
		// append() : 동적으로 html 태그를 추가하는 함수
		// empty() : 동적으로 html의 특정 요소 내부를 초기화하는 함수
		
		
		// 1. #lblDisplay 내부를 초기화하고 "네이버" 삽입
		$('#lblDisplay').empty(); // #lblDisplay 자체가 아닌 내부의 <b> 태그 삭제
		
		var strHtml = $("<a href = '#'>네이버</a><hr/>");
		$('#lblDisplay').append(strHtml);
		
		// 2. #btnCreate 클릭 시 #lblTable에 테이블 추가
		$('#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++) {
				strTable = strTable + "<tr>";	
				for(var j = 0; j < col; j++) {
					strTable += "<td>" + (i+1) + "행" + (j+1) + "열 </td>";
				}
				strTable += "</tr>";
			}
			
			$('#lblTable').append(strTable);
			$('tr:odd').addClass('Yellow');
			$('tr: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>


2) 특정 용어에 대해서 번호 붙이기

<!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() {
		$('.term').each(function(idx) {
			$(this).append("<sub>" + (idx+1) + "</sub>");
		});
	});
</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>


2. insertAfter() or 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() {
		// 어떤 요소를.insertAfter('어느 요소 뒤에')
		$('<hr />').insertAfter(".Content"); 
        //Content 클래스 뒤에 구분선을 추가
		
		// 어느 요소 앞에.before('어떤 요소를')
		$('p.Chapter:gt(0)').before("<a href = '#'>TOP</a>"); 
        //p 태그의 Chapter의 인덱스가 0보다 큰 요소 앞에 TOP 추가 

	});
</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>


3. 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() {
		// 어떤 요소를 .wrap('어떤 요소로') 감싸는 함수
		$('h3').wrap("<u></u");
		
		$('<ol type = "1" id = "community"> </ol>').insertAfter('a:eq(0)');
		
		$('a').each(function(idx) {
			$(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>


4. 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() => 요소 복제만 하는 함수
			$('#menu').clone().insertBefore('#submenu');
	});
</script>

</head>

<body>
	<div id="menu">HOME About</div>

	<div id="content">상단 메뉴를 아래 하단메뉴에 복사</div>

	<div id="submenu">여기는 하단메뉴 들어오는 곳</div>

</body>

</html>


5. 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() {
		// 어떤 요소를 .replace('어떤 요소로'): 변경
		
		$('button').click(function() {
			$(this).replaceWith("<div>" + $(this).text() + "</div>");
		});
		
	});
</script>

</head>

<body>

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

</body>

</html>



6. remove() : 검색된 요소를 완전히 제거

<!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() {
		// 제거할 요소.remove() : 실제 요소가 삭제(제거)
		$('#btnEmpty').click(function() {
			$('div').empty();
			$('div').append("<b>테스트</b>");
		})
		
		$('#btnRemove').click(function() {
			$('div').remove;
		})
		
		
	});
</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>

 

'WEB > jQuery' 카테고리의 다른 글

[jQuery] 비동기식 페이지 로드, load()  (0) 2021.06.07
[jQuery] Effects  (0) 2021.06.07
[jQuery] Traversing  (0) 2021.06.07
[jQuery] bind & unbind  (0) 2021.06.07
[jQuery] 다양한 Selector 이용  (0) 2021.06.07
Comments