• 회원가입
  • 로그인
  • 구글아이디로 로그인

[Selector] JQ - :first-child 가상선택자 - 첫번째 자식요소 선택. (= 퍼스트 차일드 선택자)

목차
  1. :first-child 예제 - 그 부모의 첫 번째 자식인 p 요소
  2. :first-child 정의
  3. :first-child 구문
  4. :first-child 예제 - 모든 div의 첫 번째 p 요소 선택
  5. :first-child 예제 - cf. :first
  6. :first-child 예제 - cf. :first-of-type

 

:first-child 예제 - 그 부모의 첫 번째 자식인 p 요소

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("p:first-child").css("background-color", "yellow");

});

</script>


<p>홈짱닷컴 Homzzang.com.</p>


<div style="border:1px solid;">

  <p>홈페이지 제작관리 강의.</p>

  <p>그누보드/영카트 강의.</p>

</div><br>


<div style="border:1px solid;">

  <span>HTML</span>

  <p>CSS</p>

  <p>JS</p>

</div>


<p>PHP</p>

 

결과보기

 

:first-child 정의

 

그 부모의 첫 번째 자식 요소인 모든 요소 선택.

 


 

1.

다른 선택자와 결합해 첫 번째 자식 유형 한정 가능.

만약, 첫 번째 자식이 아니면, 해당 안 함. (위 예제.)

 

2. cf 함수.

:last-child 선택자 : 그 부모의 마지막 자식 요소인 모든 요소 선택.

 

 

:first-child 구문

 

$(":first-child")

 

 

:first-child 예제 - 모든 div의 첫 번째 p 요소 선택

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("div p:first-child").css("background-color", "yellow");

});

</script>


<p>홈짱닷컴 Homzzang.com</p>


<div style="border:1px solid;">

  <p>HTML</p>

  <p>구조</p>

</div><br>


<div style="border:1px solid;">

  <p>CSS</p>

  <p>디자인</p>

</div>


<p>홈페이지 제작관리 강의</p>


결과보기

 

:first-child 예제 - cf. :first

:first 선택자 : 맨 처음 요소만 선택.

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("#btn1").click(function(){

    $("p:first").css("background-color", "red");

  });

  $("#btn2").click(function(){

    $("p:first-child").css("background-color", "yellow");

  });

});

</script>


<button id="btn1">:first</button>

<button id="btn2">:first-child</button><br><br>


<div style="border:1px solid">

  <p>홈짱닷컴</p>

  <p>Homzzang.com</p>

</div><br>


<div style="border:1px solid">

  <p>코딩언어.</p>

  <p>빌더서버.</p>

</div>

 

결과보기

 

:first-child 예제 - cf. :first-of-type

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("button").click(function(){

    var btn = $(this).text();

    $("p").css("background-color", "white"); 

    $("p" + btn).css("background-color", "yellow"); 

  });

});

</script>


<p>홈짱닷컴</p>


<div style="border:1px solid;">

  <p>HTML</p>

  <p>구조</p>

</div><br>


<div style="border:1px solid;">

  <span>CSS</span>

  <p>디자인</p>

  <p>구조 보충</p>

  <span>무료</span>

</div><br>


<div style="border:1px solid">

  <p>JS</p>

  <p>기능</p>

</div>


<p>홈페이지 제작관리 강의</p>


<button>:first</button>

<button>:first-child</button>

<button>:first-of-type</button><br><br>


결과보기


방문 감사합니다. (즐겨찾기 등록: Ctrl + D)

분류 제목
게시물이 없습니다.
목록
찾아주셔서 감사합니다. Since 2012