closest()는 특정 요소부터 시작해서 부모 요소들을 차례로 탐색하여, 지정한 선택자와 일치하는 가장 가까운 조상 요소를 찾으며,
이 메서드는 DOM 트리 위로 탐색을 진행한다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery closest() Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
// 버튼의 부모 중 가장 가까운 div 요소를 찾습니다.
var closestDiv = $(this).closest("div");
closestDiv.css("border", "2px solid red");
});
});
</script>
</head>
<body>
<div>
<p>Paragraph 1</p>
<div>
<p>Paragraph 2</p> //-> css효과가 적용되는 태그
<button>Find Closest Div</button>
</div>
</div>
</body>
</html>
이 메서드들도 DOM 트리를 따라 이동하면서 특정 방향으로 이동한다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.grandchild2 {
background-color: blue;
color: white;
padding: 5px;
}
</style>
</head>
<body>
<div class="parent">
<div class="child1">
<div class="grandchild1">grandchild1</div>
<div class="grandchild2">grandchild2</div>
</div>
<div class="child2">child2</div>
</div>
<script>
$(document).ready(function() {
// .grandchild1 요소를 선택하고, 가장 가까운 .parent 요소를 선택합니다.
var parent = $(".grandchild1").closest(".parent");
// 선택한 .parent 요소로부터 .child2 요소를 선택합니다.
var child2 = parent.find(".child2");
// 선택한 .child2 요소의 형제 요소로부터 .child1 요소를 선택합니다.
var child1 = child2.prev();
// 선택한 .child1 요소의 자식 요소로부터 .grandchild2 요소를 선택합니다.
var grandchild2 = child1.find(".grandchild2");
// 선택한 .grandchild2 요소를 조작합니다.
grandchild2.css("background-color", "red");
});
</script>
</body>
</html>