jQuery의 추가적인 선택자에 대해 알아보자
잠깐!
들어가기 전에 파일이 바뀔 때마다 반드시 라이브러리 연결해 주기
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>추가적인 선택자</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <!-- 온라인 방식 -->
</head>
자손 선택자(>)와 후손선택자( )
👉🏻 a>b: 자손선택자 => a의 자손들 중에서 b에 해당하는 요소를 선택
👉🏻 a b: 후손선택자 => a의 후손들(자손 포함) 중에서 b에 해당하는 요소를 선택
<div style="border : 1px solid black;">
<ul>자손1
<li>div의 후손이면서 ul의 자손1</li>
<li>div의 후손이면서 ul의 자손2</li>
<li class="ch">div의 후손이면서 ul의 자손3</li>
<li class="ch">div의 후손이면서 ul의 자손4</li>
<li>
<h3>div / ul의 후손이면서 li의 자손</h3>
</li>
</ul>
<h3>자손2</h3>
<h3 class="ch">자손3</h3>
</div>
<script>
$(function() {
$("div>h3").css("color", "lightblue"); // div의 자손들 중에서 h3만 선택
$("div h3").css("backgroundColor", "violet"); // div의 후손들 중에서 h3만 선택
// 밑의 3가지는 모두 동일한 스타일을 지정함!
// $("li>h3").css("color", "red");
// $("ul h3").css("color", "red");
$("ul>li>h3").css("color", "red");
// ul의 자손들 중에서 클래스명이 ch인 것들만 선택하겠음
$("ul>.ch").css("backgroundColor", "yellow");
// li의 후손들 중에서 클래스명이 ch인 것들만 선택하겠음
$("li .ch").css("color", "green"); // 해당 요소가 없는 경우 아무 변화 없음
// li 중에서 클래스 속성이 ch인 것들만 선택하겠음
$("li.ch").css("color", "green");
// 태그명이 li이면서 class명이 ch인 것
// => 후손은 띄어쓰기 있어야 함! 주의할 것!
});
</script>
속성 선택자
👉🏻 선택자[속성]: 특정 속성을 가지고 있는 모든 요소 선택
👉🏻 선택자[속성=속성값]: 속성값이 특정값과 "일치"하는 모든 요소 선택
👉🏻 선택자[속성~=속성값]: 속성값에 속성값을 "단어로써 포함"하는 요소 선택 (띄어쓰기 기준)
👉🏻 선택자[속성^=속성값]: 속성값이 해당 값으로 "시작"하는 요소 선택
👉🏻 선택자[속성$=속성값]: 속성값이 해당 값으로 "끝"나는 요소 선택
👉🏻 선택자[속성*=속성값]: 속성값에 해당 값을 "포함"하는 요소 선택
<!-- input[type=]*5 + Enter -->
<input type="text"> <br>
<input type="number" class="test test1"> <br>
<input type="radio"> <br>
<input type="checkbox"> <br>
<input type="button" value="button" class="test2"> <br>
<script>
$(function(){
// 선택자[속성] : 해당 속성을 가지고 있는 요소를 선택
$("input[class]").css("backgroundColor", "red");
// 선택자[속성=속성값]: 속성값이 해당 값과 "일치"하는 모든 요소 선택
$("input[type=text]").val("change value");
// .val() : value 속성과 관련된 기능을 수행하는 메소드
// 선택자[속성~=속성값]: 속성값에 해당 값을 "단어로써 포함"하는 모든 요소 선택
$("input[class~=test]").val("1234");
// 선택자[속성^=속성값]: 속성값이 해당 값으로 "시작"하는 요소 선택
$("input[type^=ra]").attr("checked", true);
// .attr() : 그 이외의 속성들과 관련된 기능을 수행
// 선택자[속성$=속성값]: 속성값이 해당 값으로 "끝"나는 요소 선택
$("input[type$=box]").attr("checked", true);
// 선택자[속성*=속성값]: 속성값에 해당 값을 "포함"하는 요소 선택
$("input[class*=st2]").css("width", "100px");
$("input[class*=st2]").css("height", "100px");
$("input[class*=st2]").val("버튼");
// 다음과 같이 연속으로 메소드를 호출할 수도 있음 (메소드체이닝)
$("input[class*=st2]").css("width","50px").css("height", "50px").val("btn");
});
</script>
입력 양식 선택자(input 태그의 type 속성에 따라서 요소를 선택)
👉🏻 : type속성값으로 표기
텍스트 상자: <input type="text"> <br>
일반 버튼: <input type="button"> <br>
체크박스: <input type="checkbox"> <br>
첨부파일: <input type="file"> <br>
비밀번호: <input type="password"> <br>
라디오 버튼: <input type="radio"> <br>
초기화 버튼: <input type="reset"> <br>
제출 버튼 <input type="submit"> <br>
<script>
$(function() {
// :type속성값
// input[type=xxx] 와 같은 의미
$(":text").css("backgroundColor", "red");
// $(":button").css("width", "200px").css("height", "200px").val("왕버튼");
// 부여하고자 하는 스타일에 대해서 객체 형태로 다음과 같이 써도 됨!
$(":button").css({width:"200px", height:"200px"}).val("왕버튼");
$(":checkbox").attr("checked", true);
$(":file").css("backgroundColor", "yellowgreen");
$(":password").css("backgroundColor", "yellow");
$(":radio").attr("checked", true).css({width:"50px", height: "50px"});
$(":reset").css({backgroundColor: "blue",
color: "white",
border: "none"});
$(":submit").css({width: "50px",
height: "50px",
backgroundColor: "green"}).click(function() {
// alert("ㅋㅋㅋㅋ");
// 제출버튼 클릭 시 비밀번호 입력란에 작성된 값을 알람으로 띄워 보기
var value = $(":password").val();
alert(value);
// .val() 메소드의 경우 매개변수 없이 호출만 하면 해당 값을 불러오는 역할을 함
// 즉, 자바로 까지면 해당 메소드 호출 시 매개변수 전달하면 setter 역할
// 매개변수를 전달하지 않는다면 getter 역할
});
});
</script>
hover에 대한 표현법
👉🏻 mouseenter : 선택된 요소의 경계 내부로 마우스가 들어가는 순간 발생하는 이벤트
👉🏻 mouseout : 선택된 요소의 경계 밖으로 마우스가 빠져나가는 순간 발생하는 이벤트
👉🏻 $(this) : 현재 이벤트가 발생한 요소
- 표현법 1~3 모두 이렇게 표현됨! -
![]() |
![]() |
마우스를 올렸을 때 | 마우스를 뗐을 때 |
<표현법 1 - mouseenter + mouseout >
텍스트 상자: <input type="text"> <br>
일반 버튼: <input type="button"> <br>
체크박스: <input type="checkbox"> <br>
첨부파일: <input type="file"> <br>
비밀번호: <input type="password"> <br>
라디오 버튼: <input type="radio"> <br>
초기화 버튼: <input type="reset"> <br>
제출 버튼 <input type="submit"> <br>
<script>
$(function() {
// mouseenter : 선택된 요소의 경계 내부로 마우스가 들어가는 순간 발생하는 이벤트
$(":submit").mouseenter(function() {
$(this).css("backgroundColor", "pink");
});
// mouseout : 선택된 요소의 경계 밖으로 마우스가 빠져나가는 순간 발생하는 이벤트
$(":submit").mouseout(function() {
$(this).css("backgroundColor", ""); // 색상을 원래 상태로 돌려놓고 싶다는 뜻
});
});
</script>
<표현법 2 - class 속성을 이용하기>
<head>
<style>
.pinkStyle {
background-color: pink;
}
</style>
</head>
<body>
텍스트 상자: <input type="text"> <br>
일반 버튼: <input type="button"> <br>
체크박스: <input type="checkbox"> <br>
첨부파일: <input type="file"> <br>
비밀번호: <input type="password"> <br>
라디오 버튼: <input type="radio"> <br>
초기화 버튼: <input type="reset"> <br>
제출 버튼 <input type="submit"> <br>
<script>
$(function() {
// mouseenter : 선택된 요소의 경계 내부로 마우스가 들어가는 순간 발생하는 이벤트
$(":submit").mouseenter(function() {
// $(this) : 현재 이벤트가 발생한 요소
// $(this).css("backgroundColor", "pink");
$(this).addClass("pinkStyle");
// .addClass() : 선택된 요소에 클래스를 추가해 주는 메소드
});
// mouseout : 선택된 요소의 경계 밖으로 마우스가 빠져나가는 순간 발생하는 이벤트
$(":submit").mouseout(function() {
// $(this).css("backgroundColor", ""); // 색상을 원래 상태로 돌려놓고 싶다는 뜻
$(this).removeClass("pinkStyle");
// .removeClass() : 선택된 요소에 클래스를 제거해 주는 메소드
});
</script>
</body>
<표현법 3 - hover>
hover = mouseenter + mouseout
자바스크립트에서는 hover라는 이벤트가 존재하지 않지만 jQuery에서는 hover라는 이벤트 메소드를 제공해 줌
<head>
<style>
.pinkStyle {
background-color: pink;
}
</style>
</head>
<body>
텍스트 상자: <input type="text"> <br>
일반 버튼: <input type="button"> <br>
체크박스: <input type="checkbox"> <br>
첨부파일: <input type="file"> <br>
비밀번호: <input type="password"> <br>
라디오 버튼: <input type="radio"> <br>
초기화 버튼: <input type="reset"> <br>
제출 버튼 <input type="submit"> <br>
<script>
$(function() {
$(":submit").hover(function() {
$(this).addClass("pinkStyle"); // mouseenter에 대한 이벤트 핸들러
}, function() {
$(this).removeClass("pinkStyle"); // mouseout에 대한 이벤트 핸들러
});
});
</script>
</body>
상태(checked, selected, disabled, enabled) 선택자
1) checked 상태 선택자
👉🏻 체크되어 있는 입력 양식을 선택
input:checked
취미:
<!-- input[type=checkbox name=hobby value=]*3 + Enter -->
<input type="checkbox" name="hobby" value="game">게임
<input type="checkbox" name="hobby" value="movie">영화
<input type="checkbox" name="hobby" value="music">음악
<br>
<button type="button" id="btn">실행확인</button>
<script>
$(function() {
// 버튼 클릭 시 현재 checked 상태인 요소를 선택해서 스타일 부여
/*
document.getElementById("btn").onclick= function() {
};
*/
$("#btn").click(function() {
$("input:checked").css({width:"50px", height:"50px"});
});
});
</script>
2) selected 상태 선택자 (selected>option)
👉🏻 option 요소 중 선택된 태그만 선택
option:selected
국가:
<select name="national">
<option value="X">선택안함</option>
<option value="KO">한국</option>
<option value="US">미국</option>
<option value="RU">러시아</option>
</select>
<button onclick="test();">확인</button>
<br>
선택한 나라: <label id="result">선택안함</label>
<script>
function test() {
// option:selected
// 현재 선택되어진 (selected 상태인) 목록값 가져옴
// console.log($("option:selected").val()); // value 값, 한국 선택 시 => 'KO' 찍힘
console.log($("option:selected").html()); // // 시작태그와 종료태그 사이의 innerHTML 값, 미국 선택 시 => '미국' 찍힘
$("#result").html($("option:selected").val()); // 러시아 선택 후 확인 버튼 클릭 시 => 선택한 나라: RU
$("#result").html($("option:selected").html()); // 한국 선택 후 확인 버튼 클릭 시 => 선택한 나라: 한국
}
</script>
![]() |
![]() |
3) disabled, enabled 상태 선택자 (input 요소들, button 요소들 등등)
👉🏻 활성화 / 비활성화된 입력 양식을 선택
선택자>:enabled
선택자>:disabled
<div id="wrap">
활성화 텍스트 상자: <input type="text"> <br>
비활성화 텍스트 상자: <input type="text" disabled> <br>
활성화 버튼: <input type="button" value="활성화버튼"> <br>
비활성화 버튼: <input type="button" vluae="비활성화버튼" disabled> <br>
버튼 태그로써: <button>활성화버튼</button> <br>
버튼 태그로써: <button disabled>비활성화버튼</button>
</div>
<script>
$(function() {
// 아이디가 wrap인 자식들 중 enabled 속성을 가진 애들만 스타일 줘!
$("#wrap>:enabled").css("backgroundColor", "yellowgreen");
// 아이디가 wrap인 자식들 중 disabled 속성을 가진 애들만 스타일 줘!
$("#wrap>:disabled").css("backgroundColor", "orangered");
});
</script>