Notice
Recent Posts
Recent Comments
Link
SeouliteLab
jQuery의 .wrap() 메소드: 요소 감싸기 본문
다양한 .wrap() 메소드 예제
jQuery의 .wrap()
메소드는 선택한 요소들을 다른 요소로 감싸는 역할을 합니다. 이를 통해 웹 페이지의 구조를 동적으로 변경할 수 있습니다. 아래 예제들을 통해 이 메소드의 활용법을 살펴보겠습니다.
예제 1: 기본적인 사용법
<!DOCTYPE html>
<html>
<head>
<title>jQuery .wrap() 예제</title>
<style>
.wrapper {
border: 2px solid red;
padding: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("p").wrap("<div class='wrapper'></div>");
});
</script>
</head>
<body>
<p>요소를 감싸는 div 요소</p>
<!-- 출력 결과: ("p" 요소가 "<div class='wrapper'></div>"로 감싸짐) -->
</body>
</html>
예제 2: 여러 요소에 대한 감싸기
<!DOCTYPE html>
<html>
<head>
<title>jQuery .wrap() 예제</title>
<style>
.wrapper {
border: 2px solid blue;
padding: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("p").wrapAll("<div class='wrapper'></div>");
});
</script>
</head>
<body>
<p>첫 번째 단락</p>
<p>두 번째 단락</p>
<!-- 출력 결과: (모든 "p" 요소가 "<div class='wrapper'></div>"로 감싸짐) -->
</body>
</html>
예제 3: 부모 요소 감싸기
<!DOCTYPE html>
<html>
<head>
<title>jQuery .wrap() 예제</title>
<style>
.wrapper {
border: 2px solid green;
padding: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("p").parent().wrap("<div class='wrapper'></div>");
});
</script>
</head>
<body>
<div>
<p>부모 요소를 감싸는 div 요소</p>
</div>
<!-- 출력 결과: ("div" 요소의 부모 요소가 "<div class='wrapper'></div>"로 감싸짐) -->
</body>
</html>
예제 4: 동적으로 감싸기
<!DOCTYPE html>
<html>
<head>
<title>jQuery .wrap() 예제</title>
<style>
.wrapper {
border: 2px solid orange;
padding: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("<div class='wrapper'></div>").insertAfter("p").wrap("p");
});
</script>
</head>
<body>
<p>요소를 감싸는 div 요소 앞에 추가됨</p>
<!-- 출력 결과: ("div" 요소가 "<p></p>"로 감싸짐) -->
</body>
</html>
예제 5: 클래스 추가 후 감싸기
<!DOCTYPE html>
<html>
<head>
<title>jQuery .wrap() 예제</title>
<style>
.highlight {
background-color: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("p").addClass("highlight").wrap("<div class='wrapper'></div>");
});
</script>
</head>
<body>
<p>요소를 감싸는 div 요소에 클래스 추가됨</p>
<!-- 출력 결과: ("p" 요소가 "<div class='wrapper'></div>"로 감싸지고, "highlight" 클래스가 추가됨) -->
</body>
</html>
.wrap()
메소드를 사용하면 선택한 요소들을 다른 요소로 감싸는 작업을 할 수 있습니다. 이를 통해 웹 페이지의 구조를 동적으로 변경하거나 스타일을 적용할 수 있으며, 위 예제들을 통해 이 메소드의 활용법을 익혀보세요.
'프로그래밍' 카테고리의 다른 글
jQuery의 .wrapInner() 메소드: 내부 요소 감싸기 (0) | 2024.04.08 |
---|---|
jQuery의 .wrapAll() 메소드: 여러 요소를 감싸기 (0) | 2024.04.08 |
jQuery의 .unwrap() 메소드: 부모 요소 제거하기 (0) | 2024.04.08 |
jQuery의 .text() 메소드: 텍스트 내용 설정 및 반환하기 (0) | 2024.04.08 |
jQuery의 .replaceWith() 메소드: 요소 교체하기 (0) | 2024.04.08 |