jQuery 요소 선택방법

  • 순수 자바스크립트 방식
document.getElementById("아이디명")
document.getElementByTagName("태그명")
document.getElementByClassName("클래스명")
  • jQuery 방식
$("#아이디명")
$("태그명")
$(".클래스명")

선택된 요소에 속성값을 변경하고자 할때

  • 순수 자바스크립트 방식
해당 속성에 접근 후
스타일 관련 | .style.스타일 속성 = "변경값"
내용 관련 | .innerHTML = "변경값"
이벤트관련 .on이벤트명 = function(){};
  • jQuery 방식
선택 요소 메소드 이용
.css("스타일속성","변경값");
.이벤트명(function(){});

추가적인 선택자

  • 자손선택자(>)와 후손 선택자()
<script>
	$(function(){
		$("div>h3").css("color","red"); //div의 자손들 중에서 h3태그만 선택하겠다.
		$("div h3").css("backgroundColor","skyBlue"); //div의 후손들 중에서 h3태그만 선택하겠다.
  		$("div>ul>li>h3").css("backgroundColor","lightgray"); //div자손의 ul자손의 li$("ul>.ch").css("backgroundColor","lightpink"); //ul자손들중 ch클래스를 가진 요소만 선택하겠다.
        $("li.ch").css("color","red"); //li중에서 ch클래스를 가진 요소만 선택하겠다.자손인 h3태그만 선택하겠다.
  	});
</script>

속성 선택자

  1. 선택자[속성] : 특정 속성을 가지고 있는 모든 요소 선택
  2. 선택자[속성=특정값] : 속성값이 특정값과 "일치"하는 모든 요소 선택
  3. 선택자[속성=특정값] : 속성값이 특정값과 "일치"하는 모든 요소 선택(공백을 기준으로 한다)
  4. 선택자[속성^=특정값] : 속성값이 특정값으로 "시작"하는 요소 선택
  5. 선택자[속성$=특정값] : 속성값이 특정값으로 "끝" 나는 요소 선택
  6. 선택자[속성*=특정값] : 속성값에 특정값을 "포함" 하는 요소 선택
<script>
    $(function(){
    	$("input[class]").css("backgroundColor","red"); //input요소중 class 속성을 가진 요소 선택
        $("input[type=text]").css("backgroundColor","purple");
        $("input[type=text]").val("안녕"); // .val() : value 속성과 관련된 기능을 수행
        $("input[type^=ra]").attr("checked",true);
        $("input[type$=box").attr("checked",true);
        // .attr() : 그외의 속성들과 관련된 기능 수행
		$("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 속성에 따라서도 요소 선택)

	/*예시 input 태그 생성*/
	텍스트 상자 : <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(){
            $(":text").css("backgroundColor","red");
            //버튼의 가로세로 150px 색을 주황색으로
            $(":button").css("width","50px").css("height","50px").css("backgroundColor","orange");
  			//체크박스는 체크상태로
            $(":checkbox").attr("checked",true);
            //첨부파일은 배경을 노란색으로
            $(":file").css("backgroundColor","yellow");
            // //비밀번호는 배경을 초록색으로
            // $(":password").css("backgroundColor","green");
            //라디오버튼은 체크상태 가로 50px 세로 50px 변경
            $(":radio").css("width","50px").css("height","50px").attr("checked",true);       
            //초기화버튼은 배경을 파란색 글자 흰색 테두리 없애기
            $(":reset").css("backgroundColor","blue").css("color","white").css("border","none");
            //스타일은 객체 형태로 부여할 수 있다.
            $(":reset").css({
                 backgroundColor : "skyblue",
                 color : "white",
                 border : "none"
            });
            //제출버튼 : 클릭시 alert("안녕하시렵니까") 실행되도록 작성
            $(":submit").click(function(){
                 alert("안녕하시렵니까??");
                 비밀번호 입력란에 있는 값을 출력해서 알람으로 띄워보기
                 alert($(":password").val());
                 //.val() 함수의 경우 매개변수 없이 호출만하면 해당 값을 불러오는 역할을 한다.
            });
            //mouseenter 배경색 변경
            $(":submit").mouseenter(function(){
            $(":submit").css("backgroundColor","skyblue");
            });
            //mouseout 배경색 다른색으로 변경
            $(":submit").mouseout(function(){
            $(":submit").css("backgroundColor","");
            });
            //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");
            });
        });
    </script>

상태 선택자

  • (checked, selected, disabled, enabled)
  1. checked 선택자 (radio, checkbox)
    체크되어 있는 입력 양식을 선택
    input:checked
	/*예시 태그 생성*/
    취미 :
    <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>
	<script>
        $(function(){
            //버튼을 클릭했을때 체크박스에 체크되어있는 요소를 스타일 변경하기
            /*
            $("#btn").click(function(){
            $("input:checked").css({width:"50px",height:"50px"});
            */
            //checkbox 요소들에 변화(change이벤트)가 생기면 실행할 function
            $(":checkbox").change(function(){
                //console.log("체인지 이벤트 발생");
                //    console.log($(this).prop("value"));
                //prop("속성명") : jQuery로 선택한 속성 값을 불러오는 메소드 
                // console.log($(this).prop("checked")); checked 속성값을 불러오기 true/false
                if($(this).prop("checked")){ //만약 지금 이벤트가 발생한 요소가 체크되었다면
                    //checked 속성 값이 true라면
                    //해당 요소의 스타일 길이와 높이를 변경하겠다            
     				$(this).css({width:"50px",height:"50px"});
                }else{ //아니라면 즉 checked속성의 값이 false라면            
      				$(this).css({width:"",height:""}); //값을 비워서 초기화
                }
            })
        });
    </script>
  1. selected 상태 선택자(selected>option)
    option 객체 중 선택된 태그를 선택
    option : selected
	/*예시 태그 생성*/
	국가 :
    <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" for="">선택안함</label>
	<script>
        function test1(){
            //현재 선택되어 있는 값 가져오기
            console.log($("option:selected").val()); //value값
            //시작태그와 종료태그 사이에 있는 텍스트값을 가져온다 innerHTML 값
            console.log($("option:selected").html());
            //label에다가 선택된 option의 값이나 innerHTML 텍스트 넣기
       		$("#result").html($("option:selected").html());
        }
    </script>
  1. disabled,enabled 상태 선택자(input요소들,button등등)
    활성화/비활성화된 입력 양식을 선택
    #아이디명>:enabled
    #아이디명>:disabled
    .클래스명>:enabled
    .클래스명>:disabled
	/*예시 태그 생성*/
	<div id="wrap">
        활성화 텍스트 상자 : <input type="text"> <br>
        비활성화 텍스트 상자 : <input type="text" disabled> <br>
        활성화 버튼 : <input type="button" value="활성화버튼"> <br>
        비활성화 버튼 : <input type="button" value="비활성화버튼" disabled> <br>
    </div>
	<script>
        $(function(){
            $("#wrap>:enabled").css("backgroundColor","yellow");
            $("#wrap>:disabled").css("backgroundColor","lightblue");
        });
    </script>

필터링 관련 선택자 및 메소드

  • 필터 관련 선택자
/*예시 테이블 생성*/
<table border="1">
        <!-- (tr>td*3)*5 -->
        <tr>
            <th>이름</th>
            <th>혈액형</th>
            <th>거주지</th>
        </tr>
        <tr>
            <td>박명수</td>
            <td>AB</td>
            <td>서울</td>
        </tr>
        <tr>
            <td>유재석</td>
            <td>O</td>
            <td>경기</td>
        </tr>
        <tr>
            <td>노홍철</td>
            <td>B</td>
            <td>인천</td>
        </tr>
        <tr>
            <td>정준하</td>
            <td>A</td>
            <td>부산</td>
        </tr>
        <tr>
            <td colspan="2">총 인원</td>
            <td>4명</td>
        </tr>
    </table>
	<script>
        $(function(){
            $("tr:first").css("backgroundColor","black").css("color","white"); //tr태그의 첫번째
            $("tr:last").css({backgroundColor:"red",color:"darkblue"}); //tr태그의 마지막
            $("tr:even").css("backgroundColor","lightgray"); //짝수번째 행 (0부터 시작)
            $("tr:odd").css("backgroundColor","lightyellow"); //홀수번째 행
        });
    </script>
  • 필터링에 관련된 메소드
    기준이 되는 요소중에서 특정 요소만을 걸러서 선택해주는 메소드
    first(), last(), filter(), eq(), not();
	/*예시 태그 생성*/
	<h4 class="test">test-1</h4>
    <h4 class="test">test-2</h4>
    <h4 class="test">test-3</h4>
    <h4 class="test">test-4</h4>
    <h4>test-5</h4>
    <h4 class="test">test-6</h4>
	<script>
        $(function(){
            $("h4").first().css("font-size","20px"); //h4 요소들 중 가장 처음요소를 선택
            $("h4").last().css("font-size","10px"); //h4 요소들 중 가장 마지막 요소
            $("h4").filter(".test").html("선택받았습니다.."); //h4요소중 test클래스를 가진 요소 선택
            $("h4").not(".test").css("color","red"); //h4요소중 test클래스 아닌 요소 선택
            $("h4").eq(1).text("eq로 선택됨"); //0부터 시작해서 해당 요소를 선택
        });
    </script>
	/*예시 태그 생성*/
	<div class="test2">테스트1</div>
    <div class="test2">테스트2</div>
    <div>테스트3</div>
    <div class="test2">테스트4</div>
    <div class="test2">테스트5</div>
	<script>
        $(function(){
            //첫번째 요소만 배경색 빨간색 글자색 하얀색 변경
            $("div").first().css({
                backgroundColor : "red",
                color : "white"
            });
            //마지막 요소만 배경색 파란색 글자색 빨간색 변경
            $("div").last().css({
                backgroundColor : "blue",
                color : "red"
            });
            //class가 test2가 아닌 div 요소 글자색 노란색 변경
            $("div").not(".test2").css("color","yellow");
            //class가 test2인 div요소 배경색 초록색 변경
            $("div").filter(".test2").css("backgroundColor","green");
            //4번째요소 width height 200px border 1px 주기
            $("div").eq(3).css({
                width : "200px",
                height : "200px",
                border : "1px solid black"
            });
        });
    </script>
profile
늦었으니 더 빠르게!

0개의 댓글