고래씌

[jQuery] 6. 탐색(순회) 메소드 - 자손 본문

Front-End/jQuery

[jQuery] 6. 탐색(순회) 메소드 - 자손

고래씌 2023. 11. 15. 17:03

▶ head 태그 => 모든 class wrap에 아래와 같은 style 부여

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>06_탐색(순회)메소드_자손</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

    <style>
        .wrap, .wrap *{
            border : 1px solid lightgray;
            display : block;
            margin: 15px;
            padding:15px;
            color: gray; 
        }
    </style>

</head>

 

 

1. 탐색(순회) 메소드

- 자손 메소드 : 기준이 되는 요소의 하위요소들을 선택할 수 있는 메소드

 

 

- $("선택자").children()
  선택된 요소의 모든 자손(바로 하위)요소들을 선택

 


- $("선택자").children("선택자")
  선택된 요소의 모든 자손요소들 중에서 제시한 선택자와 일치하는 요소들만 선택

 


- $("선택자").find("선택자")

  선택된 요소의 모든 후손요소들 중에서 제시한 값과 일치하는 요소들만 선택

 

 

$(".wrap").children().css(style1);

☞ 바로 wrap 클래스의 자손인 요소에 styel1 속성 적용

 

 

$(".wrap").children().children().css(style2);

 

☞ 바로 wrap 클래스의 자손, 자손인 요소에 styel2 속성 적용

 

 

$(".wrap").children().children('ul').css(style3);

 

☞ wrap 클래스의 자손이면서 그 아래 자손이 ul태그인 요소 style3 적용

 

 

▶ 다음 li(엄마) , p 아빠에 style 적용을 하려면 childern을 3개나 써줘야하는데, 이경우 코드가 너무 보기가 안좋다.

이런 경우, find함수를 이용하며 된다!

            $(".wrap").find("li").css(style4);
            $(".wrap").find("span").css(style5);

 

 

☞  find가 훨씬 더 간편한 것을 볼 수 있다!

 

 

    <script>
        $(function(){
            const style1 = {color:"red", border:"2px solid red"};
            const style2 = {color:"blue", border:"2px solid blue"};
            const style3 = {color:"green", border:"2px solid green"};
            const style4 = {color:"orange", border:"2px solid orange"};
            const style5 = {color:"purple", border:"2px solid purple"};


            $(".wrap").children().css(style1);
            $(".wrap").children().children().css(style2);
            $(".wrap").children().children('ul').css(style3);


            // $(".wrap").children().children().children('li').css(style4);
            $(".wrap").find("li").css(style4);
            $(".wrap").find("span").css(style5);

        })
    </script>