Notice
Recent Posts
Recent Comments
Link
SeouliteLab
jQuery의 :has() 선택자 활용하기 본문
jQuery의 :has() 선택자는 지정한 선택자로 요소를 포함하는 요소를 선택하는 데 사용됩니다. 이를 활용하여 특정 조건을 만족하는 요소를 선택하고 조작할 수 있습니다.
예제 1: 특정 클래스를 포함한 <div> 요소 선택하기
<!DOCTYPE html>
<html>
<head>
<title>특정 클래스를 포함한 \<div> 요소 선택하기</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("div:has(.highlight)").css("border", "2px solid red");
});
</script>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<div>일반 요소</div>
<div class="highlight">하이라이트된 요소</div>
</body>
</html>
설명: 위 예제는 클래스가 "highlight"인 요소를 포함한 <div> 요소를 선택하여 테두리를 빨간색으로 변경합니다.
예제 2: 특정 자식 요소를 포함하는 <div> 요소 선택하기
<!DOCTYPE html>
<html>
<head>
<title>특정 자식 요소를 포함하는 \<div> 요소 선택하기</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("div:has(p)").css("background-color", "lightblue");
});
</script>
</head>
<body>
<div>
<p>내용</p>
</div>
<div>
<span>내용</span>
</div>
</body>
</html>
설명: 이 예제는 <div> 요소 중 <p> 자식 요소를 포함하는 요소를 선택하여 배경색을 연보라색으로 변경합니다.
예제 3: 특정 속성을 포함하는 <a> 요소 선택하기
<!DOCTYPE html>
<html>
<head>
<title>특정 속성을 포함하는 \<a> 요소 선택하기</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("a:has([target])").css("font-weight", "bold");
});
</script>
</head>
<body>
<a href="#">링크1</a>
<a href="#" target="_blank">새 창으로 열리는 링크</a>
</body>
</html>
이 예제는 target 속성을 포함하는 <a> 요소를 선택하여 글꼴을 굵게 표시합니다.
'프로그래밍' 카테고리의 다른 글
jQuery의 :hidden 선택자 활용하기 (0) | 2024.04.12 |
---|---|
jQuery의 :header 선택자 활용하기 (0) | 2024.04.12 |
jQuery의 속성 선택자 [name] 활용하기 (0) | 2024.04.12 |
jQuery의 :gt() 선택자 활용하기 (0) | 2024.04.12 |
jQuery의 :focus 선택자 활용하기 (0) | 2024.04.12 |