jQuery :: 추가적인 선택자

김병철·2022년 11월 27일
0

jQuery

목록 보기
3/7

jQuery

jQuery 추가적인 선택자

# 자손 선택자('>')와 후손 선택자 (' ')

자손은 바로 아래에 있는 것

후손은 아래에 있는 것들

  • html 코드 :
<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의  class="ch"자손</h3>
        </li>

    </ul>
    <h3>자손2</h3>
    <h3 class="ch">자손3</h3>
</div>
  • javascript 코드 :
$(function(){
  	//div의 자손들 중에서 h3태그만 색을 red로 변경
    $("div>h3").css("color","red"); 
  	//div의 후손들 중에서 h3태그만 선택하여 배경색을 skyblude로 변경
    $("div h3").css("backgroundColor","skyblue");
  	//div자손의 ul자손의 li자손인 h3태그만 배경색을 lightgray로 변경
    $("div>ul>li>h3").css("backgroundColor","lightgray");
  	//ul자손들중 ch클래스를 가진 요소만 배경색을 lightpink로 변경
    $("ul>.ch").css("backgroundColor","lightpink");
  	//li중에서 ch클래스를 가진 요소만 색을 red로 변경
    $("li.ch").css("color","red");
});
  • html 출력 결과 :

# 속성 선택자

  • 선택자[속성] : 특정 속성을 갖고 있는 모든 요소 선택
  • 선택자[속성=특정값] : 속성값이 특정값과 '일치'하는 모든 요소 선택
  • 선택자[속성~=특정값] : 속성값에 특정값을 '단어로써 포함'하는 요소 선택(공백 기준)
  • 선택자[속성^=특정값] : 속성값이 특정값으로 '시작'하는 요소 선택
  • 선택자[속성$=특정값] : 속성값이 특정값으로 '끝'나는 요소 선택
  • 선택자[속성*=특정값] : 속성값에 특정값을 '포함'하는 요소 선택

# jQuery 코드 변경에 따른 html 변화 확인

  • html 코드 :
<input type="text">text 입력<br>
<input type="number" class="test test1">number 입력<br>
<input type="radio">radio 입력<br>
<input type="checkbox">checkbox 입력<br>
<input type="button" value="버튼" class="test2">button 입력<br>
  • 초기 html 출력 :

input요소 중 class 속성을 가진 number타입, button타입의 배경색이 red로 변경

  • jQuery 코드 :
$(function(){
	$("input[class]").css("backgroundColor","red");
}
  • html 출력 결과 :

input요소 중 type이 text인 것만 배경색을 purple로 변경

  • jQuery 코드 :
$(function(){
	$("input[type=text]").css("backgroundColor","purple");
}
  • html 출력 결과 :

input요소 중 type이 text인 것의 값을 "안녕"으로 변경

  • jQuery 코드 :
$(function(){
  	// .val() : value 속성과 관련된 기능을 수행
	$("input[type=text]").val("안녕");
}
  • html 출력 결과 :

input요소 중 type명이 ra로 시작하는 요소의 checked 속성을 true로 변경

  • jQuery 코드 :
$(function(){
  	// .attr() : 그외의 속성들과 관련된 기능 수행
  	$("input[type^=ra]").attr("checked",true);
}
  • html 출력 결과 :

input요소 중 type명이 'box'로 끝나는 요소의 checked 속성을 true로 변경

  • jQuery 코드 :
$(function(){
  	$("input[type$=box]").attr("checked",true);
}
  • html 출력 결과 :

input요소 중 class명이 st2를 포함하는 button요소의 width, height, val을 변경

  • jQuery 코드 :
$(function(){
  	$("input[class*=st2]").css("width","100px");
	$("input[class*=st2]").css("height","100px");
	$("input[class*=st2]").val("버튼입니다.");
}
  • html 출력 결과 :

input요소 중 class명이 st2를 포함하는 button요소의 width, height, val을 변경

  • jQuery 코드 :
$(function(){
	//다음과 같이 연속으로 메소드를 호출해서 쓸수도 있다. - 메소드 체이닝
 	$("input[class*=st2]").css("width","50px").css("height","50px").val("btn");
}
  • html 출력 결과 :

# 입력양식 선택자

input 태그의 type 속성에 따라서도 요소 선택이 가능하다.

# jQuery 코드 변경에 따른 html 변화 확인

  • html 코드 :
텍스트 상자 : <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>
<input type="submit" value="확인">

type이 text인 요소의 배경색을 red로 변경

  • javascript 코드 :
$(function(){
	$(":text").css("backgroundColor","red");
}
  • html 출력 결과 :

type이 button인 요소의 width, height, 배경색 변경

  • javascript 코드 :
$(function(){
	//버튼의 가로세로 150px 색을 주황색으로 
	$(":button").css("width","50px").css("height","50px").css("backgroundColor","orange");	
}
  • html 출력 결과 :

type이 checkbox인 요소의 checked 속성을 true로 변경

  • javascript 코드 :
$(function(){
	$(":checkbox").attr("checked",true);
}
  • html 출력 결과 :

type이 file인 요소의 배경색을 yellow로 변경

  • javascript 코드 :
$(function(){
	$(":file").css("backgroundColor","yellow");
}
  • html 출력 결과 :

type이 password인 요소의 배경색을 green으로 변경

  • javascript 코드 :
$(function(){
	$(":password").css("backgroundColor","green");
}
  • html 출력 결과 :

type이 radio인 요소의 checked, width, height 요소 변경

  • javascript 코드 :
$(function(){
	$(":radio").attr("checked",true).css("width","50px").css("height","50px");
}
  • html 출력 결과 :

type이 reset인 요소의 배경색, 색, 경계선 속성 변경

  • javascript 코드 :
$(function(){
	$(":reset").css("backgroundColor","blue").css("color","white").css("border","none");
}
  • html 출력 결과 :

type이 reset인 요소의 배경색, 색, 경계선 속성 변경

  • javascript 코드 :
$(function(){
	$(":reset").css({
		backgroundColor:"skyblue",
		color: "white",
		border : "none"
	});
}
  • html 출력 결과 :

type이 submit인 요소 클릭 시 password 타입 요소에 입력된 값을 alert창으로 출력

  • javascript 코드 :
$(function(){
	$(":submit").click(function(){
    	//비밀번호 입력란에 있는 값을 출력해서 알람으로 띄워보기
    	alert($(":password").val());
    	//.val() 함수의 경우 매개변수 없이 호출만하면 해당 값을 불러오는 역할을 한다.
	});
}
  • html 출력 결과 :


type이 submit인 요소에 마우스가 들어갈 때 배경색을 red로, 빠져나올 때는 원래 색으로 변경

  • javascript 코드 :
$(function(){
	//mouseenter 배경색 변경 
	$(":submit").mouseenter(function(){
		$(":submit").css("backgroundColor","red");
	});
	//mouseout  배경색 다른색으로 변경
	$(":submit").mouseout(function(){
		$(":submit").css("backgroundColor","");
	});
}
  • html 출력 결과 :

type이 submit인 요소에 hover 기능을 추가한다.

hover 시 type인 submit인 요소 전부에 moon 클래스를 추가한다.

  • javascript 코드 :
$(function(){
	//hover 
    $(":submit").hover(function(){ //mouseenter에 대한 이벤트 설정
        //만약 내가 동적으로 요소에 class 속성을 부여하고자 한다면?
        //addClass("클래스명") : 선택된 요소에 클래스 속성을 부여하는 메소드
        $(":submit").addClass("moon"); //중복되는 요소들이 전부 적용된다
        //이벤트가 발생한 요소만 적용시키고자 한다면 ? 
        //this를 사용 $(this)
        //$(this).addClass("moon");
        console.log($(this));
    }, function(){ //mouseout에 대한 이벤트 설정
        //removeClass() : 선택된 요소에 클래스 속성을 제거하는 메소드
        $(":submit").removeClass("moon");
        //$(this).removeClass("moon"); 
    });
}
  • html 출력 결과 :

type이 submit인 요소에 hover 기능을 추가한다.

hover 시 이벤트가 발생한 요소만 moon 클래스를 추가한다.

  • javascript 코드 :
$(function(){
	//hover 
    $(":submit").hover(function(){ //mouseenter에 대한 이벤트 설정
        //만약 내가 동적으로 요소에 class 속성을 부여하고자 한다면?
        //addClass("클래스명") : 선택된 요소에 클래스 속성을 부여하는 메소드
        //$(":submit").addClass("moon"); //중복되는 요소들이 전부 적용된다
        //이벤트가 발생한 요소만 적용시키고자 한다면 ? 
        //this를 사용 $(this)
        $(this).addClass("moon");
        console.log($(this));
    }, function(){ //mouseout에 대한 이벤트 설정
        //removeClass() : 선택된 요소에 클래스 속성을 제거하는 메소드
        //$(":submit").removeClass("moon");
        $(this).removeClass("moon"); 
    });
}
  • html 출력 결과 :

# 상태 선택자

(checked, selected, disabled, enabled)

# checked 선택자(radio, checkbox)

체크되어 있는 입력 양식을 선택
input:checked

  • html 코드 :
<input type="checkbox" name="hobby" id="game" value="game"> 게임
<input type="checkbox" name="hobby" id="movie" value="movie"> 영화
<input type="checkbox" name="hobby" id="music" value="music"> 음악
<button type="button" id="btn">실행</button>
  • 실행 전 html 출력 :

버튼을 클릭했을때 체크박스에 체크되어있는 요소를 스타일 변경

  • jQuery 코드 :
$(function(){
    $("#btn").click(function(){
        $("input:checked").css({width:"50px",height:"50px"});
    })
});
  • 실행 버튼 클릭 후 html 결과 출력 :

버튼을 클릭했을때 체크박스에 체크되어있는 요소를 스타일 변경

  • jQuery 코드 :
$(function(){
    $(":checkbox").change(function(){
		console.log($(this));
		//prop("속성명") : jquery로 선택한 속성 값을 불러오는 메소드
		if($(this).prop("checked")){ //만약 지금 이벤트가 발생한 요소가 체크되었다면 
			//checked 속성 값이 true라면 해당 요소의 스타일 길이와 높이를 변경
			$(this).css({width:"50px",height:"50px"});
		}else{//아니라면 즉 checked속성의 값이 false라면 
			$(this).css({width:"",height:""}); //값을 비워서 초기화
		}
	})
});
  • check 후 html 결과 출력 :

  • check 후 콘솔 결과 출력 :

체크하자마자 스타일이 변경된다.


# selected 선택자(select>option)

option 객체 중 선택된 태그를 선택
input:selected

  • html 코드 :
국가 : 
<select name="national" id="">
    <option value="x">선택안함</option>
    <option value="ko">한국</option>
    <option value="us">미국</option>
    <option value="eu">영국</option>
</select>

<button onclick="test1();">확인</button>

<label id="result">선택안함</label>
  • 실행 전 html 출력 :

option에서 선택된 값을 콘솔에 출력하고 html로 출력하여 확인한다.

  • jQuery 코드 :
function test1(){
    //현재 선택 되어 있는 값 가져오기
    console.log($("option:selected").val()); //value값
	//시작태그와 종료태그 사이에 있는 텍스트값을 가져온다 innerHTML 값 
    console.log($("option:selected").html());

    //label에다가 선택된 option의 값이나 innerHTML텍스트 넣기 
    $("#result").html($("option:selected").html());
}
  • 국가를 선택하고 확인 버튼 클릭 후 html 결과 출력 :

  • 콘솔창 출력 :


# disabled, enabled 상태 선택자(input요소들, button등)

활성화/비활성화된 입력 양식을 선택

  • #아이디명>:enabled
  • #아이디명>:disabled
  • .클래스명>:enabled
  • .클래스명>:disabled
  • html 코드 :
<div id="wrap">
    활성화 텍스트 상자 : <input type="text"> <br>
    비활성화 텍스트 상자 : <input type="text" disabled> <br>

    활성화 버튼 : <input type="button" value="활성화버튼"> <br>
    비활성화 버튼 : <input type="button" value="비활성화버튼" disabled> <br>
</div>

id가 wrap인 요소 중 활성화된/비활성화된 요소의 배경색 속성 변경

  • jQuery 코드 :
$(function(){
    $("#wrap>:enabled").css("background-color","lightyellow");
    $("#wrap>:disabled").css("background-color","lightblue");
});
  • html 결과 출력 :

profile
keep going on~

0개의 댓글