728x90
반응형
//태그 선택자
// jQuery 선택자는 css선택자와 같다!
$("h5").css("color", "red");
$("p").css("color", "blue");
// 자바스크립트로 했을 때
//document.getElementsByTagName("p").style.color = "green";
// -> 배열에 스타일을 적용할 수 없다!
const arr = document.getElementsByTagName("p");
for(let item of arr){
item.style.color = "green";
}
//h5, p 두 태그 동시에 배경색을 yellow으로 지정하기
$("h5,p").css("backgroundColor", "yellow");
// 클래스 선택자
// 클래스 item인 요소의 글자색을 orange로 변경
$(".item").css("color","orange");
// 클래스가 select인 요소인 배경색을 red로 변경
$(".select").css("backgroundColor","red");
// 클래스가 item, select를 동시에 가지고 있는 요소만
// 글자 크기를 50px로 변경
$(".item.select").css("fontSize","50px");
//아이디 선택자
const regExp = /^[a-z][a-zA-Z0-9]{7,19}$/
$("#input1").on("input",function(){
// on() == addEventListener
// -> 특정 이벤트 발생 시 동작(이벤트 핸들러)지정
// input 이벤트 : 입력과 관련된 모든 행위
// 1) 작성된 값이 정규 표현식에 맞는 형식인지 검사
if(regExp.test($("#input1").val())){
// $("#input1").val()
// : 아이디가 input1인 요소에 작성된 값(value)을 얻어옴
// 2) 정규식 결과에 따라 내용 출력
$("#span1").text("유효한 문자열 형식 입니다.");
$("#span1").css("color", "green");
}else{
$("#span1").text("유효하지 않은 문자열 형식 입니다.").css("color", "red");
//method chaining : 하나의 대상에 대하여 여러 메소드를 연달아 작성하는 기술
}
})
//자식, 후손 선택자
//클래스가 area인 요소의 자식중 h4 글자색 red
$(".area>h4").css("color","red");
// 클래스가 area인 요소인 후손 중 ul 후손 중에
// 클래스가 fruit인 요소의 배경색 원하는걸로 바꾸기
$(".area ul .fruit").css("backgroundColor","yellow");
//클래스가 area인 요소의 후손 중
// 클래스가 fruit인 요소의 폰트 크기를 30px로 변경
$(".area .fruit").css("fontSize","30px");
// 내용이 "딸기"인 요소를 선택해서
// 배경 빨간색, 글자는 흰색으로 변경
$(".area li>h4").css("backgroundColor","red").css("color","white");
$("#check").on("click",function(){
//name 속성 값이 gender인 요소 선택
console.log($("input[name='gender']"));
//name 속성 값이 gender인 요소중 check된 요소를 선택
// :checked -> check 된 요소만 선택
const gender = $("input[name='gender']:checked");
console.log(gender.length);
// 아무것도 check 안함 : 0
// 하나 check : 1
// radio 버튼이 하나도 선택되지 않은 경우
// "남자 또는 여자 중 하나를 선택해 주세요. 알림창"
if(gender.length==0){
alert("남자 또는 여자 중 하나를 선택해 주세요.");
}else{
// 1) 체크된 요소를 모두 얻어왔으므로
// 배열 현태로 저장된 gender 변수에서
// 0번 인덱스의 value만 얻어오기(순수 js)
console.log(gender[0].value);
// 2) 체크된 요소를 모두 얻어와도
// radio는 1개만 체크되어 있기 때문에
// 변수 한개랑 같다라고 해석하여
// 자동으로 0번 인덱스 요소에 있는 value를 얻어옴(JS + jQuery)
console.log(gender.val());
// 3) 순수 jQuery
console.log($(gender).val());
//$ (gender) : 체크된 요소만 담긴 배열 + 요소를 선택해라 기호
// --> 체크된 radio 버튼을 선택하는 jQuery 선택자
alert($(gender).val()+"자를 선택하셨습니다.");
}
})
// prop() 메소드
$("#btn1").on("click",function(){
const arr = $("input[name='hobby']");
console.log(arr.prop("checked"));
// 배열명만 적을 경우 0번 인덱스만 확인 가능
let str ="";// 체크된 요소의 value 값을 누적
for(let i=0 ; i<arr.length; i++){
//각 인덱스에 저장된 checkbox 요소가 체크되어 있는 상태인지 확인
console.log(i+ ":" +$(arr[i]).prop("checked"));
if($(arr[i]).prop("checked")){
str += $(arr[i]).val() + " ";
}
}
//체크된 요소 알림창에 띄우기
alert(str);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>02_jQuery선택자</title>
</head>
<body>
<h1>jQuery 선택자</h1>
<pre>
jQuery는 요소를 선택할 때
$("CSS 선택자") 또는 $(요소가 저장된 변수)의 형식으로 작성
* CSS 선택자로 요소를 선택한 경우
- id로 선택 시 단일 요소 반환
- class, name, 자식/후손 등으로 선택 시 배열로 반환
</pre>
<h3>태그 선택자</h3>
<h5>테스트1</h5>
<h5>테스트2</h5>
<h5>테스트3</h5>
<p>테스트4</p>
<p>테스트5</p>
<p>테스트6</p>
<hr>
<h3>클래스 선택자</h3>
<h1 class="item">test1</h1>
<h1 class="item select">test2</h1>
<h1 class="item">test3</h1>
<h1 class="select">test4</h1>
<hr>
<h3>아이디 선택자</h3>
영어 소문자 + 영어 대문자 + 숫자로만 이루어진 문자열<br>
글자수는 총 8~20글자 사이<br>
단, 첫 글자는 반드시 소문자
<input type="text" id="input1">
<span id="span1"></span>
<hr>
<h3>자식,후손 선택자</h3>
<div class="area">
<ul>
<li><h4>딸기</h4></li>
<li>바나나</li>
<li>사과</li>
<li class="fruit">오렌지</li>
<li class="fruit">포도</li>
</ul>
<h4>테스트1</h4>
<h4 class="fruit">망고</h4>
</div>
<h3>속성 선택자</h3>
<pre>
요소[속성] : 특정 속성을 가지고 있는 객체 선택
요소[속성 = 값] : 속성 안의 값이 특정 값과 같은 객체를 선택
요소[속성 ~=값] : 속성 안의 값이 특정 값을 단어로 포함하는 객체 선택
요소[속성 ^=값] : 속성 안의 값이 특정 값으로 시작하는 객체 선택
요소[속성 $=값] : 속성 안의 값이 특정 값으로 끝나는 객체 선택
요소[속성 *=값] : 속성 안의 값이 특정 값을 포함하는 객체 선택
</pre>
성별 :
<input type="radio" name="gender" id="male" value="남">
<label for="male">남자</label>
<input type="radio" name="gender" id="female" value="여">
<label for="female">여자</label>
<button type="button" id="check">확인하기</button>
<hr>
<h3>prop() 메소드</h3>
<pre>
attribute : type, name, class, id, value 등과 같이
속성값을 별도로 입력해야되는 속성
property : checked, selected와 같이
속성값이 별도로 입력되지 않은 속성
prop("속성명") : 해당 속성이 요소에 존재하면 true, 아니면 false
prop("속성명", true | false) : 해당 속성을 checked 또는 selected 상태로 변경(true) / 해제(false)
</pre>
취미 :
<input type="checkbox" name="hobby" value="football"> 축구
<input type="checkbox" name="hobby" value="game" checked> 게임
<input type="checkbox" name="hobby" value="musice"> 음악감상
<button type="button" id="btn1">확인</button>
<!-- jQuery 추가 -->
<script src="js/jquery-3.7.1.min.js"></script>
<script src="js/02_jQuery선택자.js"></script>
</body>
</html>
728x90
반응형