Jam's story

[JQuery] selector 선택자 본문

WEB/JQuery

[JQuery] selector 선택자

애플쩀 2022. 6. 13. 14:18
  1. * 모든요소
  2. # 아이디
  3. . 클래스명
  4. 클래스명
  5. 태그명
  6. :first :last
  7. :even :odd
  8. :first-child :last-child
  9. :first-of-type :last-of-type
  10. :nth-child(n) :nth-of-type(n)
  11. :only-child :only-of-type 혼자 자식일 경우 적용
  12. parent > child 직계자식
    • parent child 자식
    • parent + child 직계 뒤 형제
    • parent ~ child 뒤 형제
  13. eq(index) gt(index) lt(index) 인덱스이므로 0번부터 시작한다. gt 와 lt 는 index 를 포함하지 않는다.
  14. :not
  15. :header
  16. :animated
  17. :focus
  18. :has(선택자)
  19. :contains(문자열)
  20. :empty :parent
  21. :hidden :visible
  22. [속성명] ex) $("[type]")
  23. $("input[type=text]") $(":input") 모든 input 요소를 선택자로 사용
  24. $(":text")
  25. $(":password")
  26. $(":radio")
  27. $(":checkbox:checked")
  28. $(":submit")
  29. $(":reset")
  30. $(":button")
  31. $(":image") $(":file")
  32. disabled enabled
  33. selected
  34. checked

 

* 모든 요소 

 $(function(){
 /*        css체이닝 */
        $("*").css("border","1px solid red")
        .css("padding",20)
        .css("color","blue");

        $("*").css({
            "border":"1px solid red",
        "padding":20,
     "color":"blue"

    });
    $("div *").css({
        "background-color":"green",
        "color":"red"
    });
</script>

 

아이디명 

  $("#ptag").hide();

클래스명 

$(".box").hide();
    //클래스명이 box인 것이랑  demo 둘다 (또는) 적용시켜라
    $(".box , .demo").hide();

태그명 

 $("p").toggle();
    //p태그 또는 h3태그 또는 div를 선택자로 사용하겠다. 
    $("p, h3, div").toggle();

 

:  선택자 :first  :odd

<script>
    $(document).ready(function(){
        //모든 p태그 
        $("p").css("background-color","yellow");
        //첫번째 p태그
        $("p:first").css("background-color","yellow");
        //마지막 p태그 
        $("p:last").css("background-color","yellow");
    });
</script>
p:last라 함은 마지막 p태그를 말한다. 
예를들어  p태그가 4개가 있고, 그 다음에 div태그가 있다면 
div태그가 아닌 말그대로 마지막에 위치한 p 태그를 말한다. 

 

 

 

:even 짝수

:odd  홀수

<script>
    $("tr").css("background-color","yellow");

    $("tr:odd").css("background-color","red");
</script>

 

:first-child :last-child 

자식요소가 --태그인 것 

    <script>
        $("#btn1").click(function(){
            //모든 p태그의 첫번째 태그
            $("p:first").css("background-color","yellow");
        });
        $("#btn2").click(function(){
            //모든 첫번째자식이 p태그인것
            $("p:first-child").css("background-color","red");
        });
    </script>

 

:first-of-type :last-of-type

첫번째, 마지막 요소가 --태그인것 

     $("#btn3").click(function(){
            //첫번째 요소가  p태그인것
            $("p:first-of-type").css("background-color","green");
        });

 

:nth-child(n)  n번째 자식이 --태그인 것

:nth-of-type(n) n번째 요소가 --태그인 것

 $("p:nth-child(2)").css("background-color","red");
$("p:nth-last-of-type(2)").css("background-color","red");
    <p class="box">p안에    				//$("p:first-child")  $("p:first-of-type")
    <p class="demo">자식p태그 </p>     			// $("p:nth-of-type(2)")
</p>
<p>Lorem, ipsum dolor.</p>
<p>Rerum, rem in.</p>
<p>Asperiores, praesentium obcaecati?</p>
<p>Vitae, doloremque ullam.</p> 			//  $("p:last-of-type")
<div>div안에 
    <p>자식p태그안에 			//$("p:first-child") , $("p:first-of-type")
        <p>자식p태그2</p> 		// $("p:nth-of-type(2)")
    </p>  
</div>
<h3>ex01.html</h3>
 
:only-child , 어떤요소의 자식이 하나밖에 없을 때  
:only-of-type 같은 유형의 형제가 없을 때 
   //부모의 유일한 자식이 p태그인 선택자 
    $("p:only-child").css("background-color","red");

    //부모의 여러 자식중에 p태그만 1개 
    $("p:only-of-type").css("background-color","red");

 

스페이스 공백 자식 

> 직계자식

+ 바로 뒤 형제 

~ 바로 뒤 형제 

 //자식
    $("div p").css("background-color","yellow");

    //div의 직계자식p
    $("div > p").css("background-color","yellow");

    //div 다음 형제 태그가 p 
    $("div + p").css("background-color","yellow");

    //div 다음 형제 태그가 p 
    $("div ~ p").css("background-color","yellow");

 

eq = 

gt > 큰 값 

lt < 작은 값 

    $("p").css("background-color","yellow");
    //eq = 
    $("p:eq(4)").css("background-color","red");
    //gt> -번째보다 큰값
    $("p:gt(4)").css("background-color","red");
    //lt < -번째보다 작은값
    $("p:lt(4)").css("background-color","red");

 

:not

    $("p").not(".intro").css("background-color","blue");
    //intro클래스가 아닌 p태그 
    $("p:not(.intro)").css("background-color","blue");

 

:header

    $("h1, h2, h3, h4, h5, h6").css("background-color","yellow");
    //:header h1~h6
    $(":header").css("background-color","red");

 

animated

<body onload=" aniDiv()">
<h3>ex01_12.html</h3>
<button class="btn1">change</button>
<div>div 1</div>
<div>div 2</div>
<div>div 3</div>

<script>
    $("div:first-of-type").css("background-color","red");
    $("div:eq(1)").css("background-color","green");
    $("div:last-of-type").css("background-color","blue");

    function aniDiv(){
        $("div:eq(0)").animate({width:"50%"},"slow")
            .animate({width:"100%"},"slow",aniDiv);
    }
</script>
<script>
  $(".btn1").click(function(){
      //현재 애니메이션이 적용되는 모든 요소를 선택자로 선택 
      $("div:animated").css("background-color","yellow");
  });
</script>

 

focus()

<script>
  //  $("input[type=text]") == $(":text")
  $(":text:eq(2)").focus();

  //현재 포커스를 가진 요소를 선택자로 사용 
  $(":focus").css("background-color","red");

  
</script>

 

:has

    //$("p:has(selector)").css("background-color","yellow");
    
    //span태그를 가지고 있는 p태그
    $("p:has(span)").css("background-color","yellow");

    $("p").has("span").css("background-color","red");
    
    $("p").has("span .di").css("background-color","red");

 

:empty 비어있는 요소 

 //빈요소 td를 선택자로 사용
$("td:empty").css("background-color","red");

//비어있지 않는 요소 
$("td:not(:empty)").css("background-color","yellow");

//문자열을 포함한 자식이 잇는 모든 td 
//부모인 td
$("td:parent").css("background-color","blue");

 

 

:hidden

:visible

:root 웹문서구조에서 가장상위 -> 그래서 배경이 빨간색으로 나타남 

<p>Lorem, ipsum dolor.</p>
<p>Hic, ad iusto!</p>
<p style="display: none;">Doloremque, vel velit!</p>
<p>Nostrum, doloribus voluptates.</p>
<p>Suscipit, doloremque in!</p>

<script>
    $(":root").css("background-color","green");

    //보이지 않는 모든 p태그를 선택자로 사용 
    $("p:hidden").show(5000,function(){
          //5초동안 보이기 작업이 완료된 후에 호출되는 콜백함수
        $("p:visible").css("background-color","yellow");
    });
</script>

 

[attribute]

    //1속성값은 중요하지 않고 type 속성만 가지면 
    $("[type]").css("background-color","yellow");

    //2type 속성=text
    $("[type=text]").css("background-color","red");

    //3
    $(":text").css("backgrond-color","red");
    
    //
    $("[name=nation]").css("background-color","green");

    //
    $("[name$=nation]").css("background-color","red");

    //
    $("[name^=nation]").css("background-color","yellow");

 

:input input

:text input[type=text]

:password input[type=password]

:radio input[type=radio]

:check input[type=checkbox]

:submit

:reset

:button input[type=button]

:image input[type=image]

:file input[type=file]

 

:selected 선택된 option

:disalbed 비활성화된 요소 

:enabled 활성화된 요소 

:chekced 체크된 요소 

 

 

 

 
상대값을 정의하는 것 
기준: 현재 요소의 값 +=   -=
<script>

    //버튼누르면 오른쪽으로 이동
    $("button").click(function(){
        //div 이동 250px x좌표로 이동: 애니매이션 처리 
       // $("div").animate({left:"250px"},speed,callback);
       $("div").animate({left:"250px"});
    });
</script> 
 <script>
    //여러 속성 동시에 애니메이션 처리
    $("button").click(function(){
       
       $("div").animate({
        left:"250px",
        opacity:'0.5',
        height:"150px",
        widht:"150px"
    });
    });
</script>
<script>
    //상대값을 정의하는 것도 가능하다 
    //기준:현재 요소의 값 
    $("button").click(function(){
       
       $("div").animate({
        left:"+=50px",
        opacity:'0.5',
        height:"+=150px",
        widht:"+=150px"
    });
    });
</script>

 

 

라디오버튼 예제

<script>
    //라디오 버튼 + -선택 체크한 ㅅ후에 실행버튼 클릭
     $("button").click(function(){
        var dir=$(":radio:checked").val();
        $("div").animate({
            left:dir+'=50px'
        });
     });
</script>

 

 

 

애니메이션 감싸기 

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>2022.06.13 12:47:17</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h3>ex02_04.html</h3>
<div id="clickme">click me</div>
<!-- //크기/배경색/글씨색 -->
<a href="https://placeholder.com"><img src="https://via.placeholder.com/200x200/FF0000/FFFFFF?text=sample"
    style="position: relative;left: 10px;"></a>

<img  id="book">
<a href="https://placeholder.com"><img src="https://via.placeholder.com/150x100/000000/ffffff?text=sample"></a>
<script>
    $("#clickme").click(function(){
        //animate 첫번재는 css, speed, callback 함수 
        $("#book").animate({
            {
                width:"toggle",
                height:"toggle"
            },{
                duration:5000,
                specialEasing:{
                    width:"linear",height:"easeOutBounce"
                }
                ,complete:function(){
                    //append() appendTo()
                    //prepend() prependTo()
                    //before() 
                    //after 

                    $(this).after("<div>Animation complete</div>")
                }
            
        }
        );

    });
</script>
</body>
</html>
Comments