Frontend/jQuery

[jQuery] 순회(탐색) 메서드 :: Descendants (자손) 탐색 메서드

Deeb 2021. 11. 17. 09:36

 Descendants (자손) 탐색 메서드

 

$("선택자").children([매개변수]);
            - 선택된 요소의 모든 자식 요소를 반환
            - 매개변수가 있으면 일치하는 자식 요소만을 반환


$("선택자").find(매개변수);
            - 선택된 요소의 모든 후손 중
                매개변수와 일치하는 요소를 모두 반환

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>순회(탐색) 메서드 2</title>
    <style>
        .wrap * { /* wrap 클래스의 모든 후손 */
            border: 1px solid darkgray;
            display: block;
            padding: 5px;
            margin: 15px;
            color: gray;
        } 
        .type { width: 500px; }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="type">div (great-grand parent)
            <ul>ul (grand parent)
                <li>li (direct parent)
                    <span>span</span>
                </li>
            </ul>
        </div>

        <div class="type">div (grand parent)
            <p>p (direct parent)
                <span>span</span>
            </p>
        </div>
    </div>

    <div id="test">테스트</div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    
    <script>
        $(function(){
            // #test 요소의 배경색 "green", 글자색을 "white"으로 변경
            // 기존 방법 : css코드의 중복
            // $("#test").css("backgroundColor", "green").css("color", "white");

            const testStyle = {backgroundColor : "green", color : "white"}; // JS 객체 
            $("#test").css(testStyle);
            // css() 메서드의 매개변수로 객체를 전달하면  
            // 여러 스타일이 한 번에 적용된다.

            const style1 = {border : "2px solid red", color : "red"};
            const style2 = {border : "2px solid orange", color : "orange"};
            const style3 = {border : "2px solid yellow", color : "yellow"};
            const style4 = {border : "2px solid green", color : "green"};
            const style5 = {border : "2px solid blue", color : "blue"};
            
            // 클래스가 wrap인 요소의 모든 자식의 스타일을 style1으로 변경
            // -> children()
            $(".wrap").children().css(style1);

            // 클래스가 wrap인 요소 기준으로 
            // ul, p태그의 스타일을 style2로 변경
            $(".wrap").children().children().css(style2);

            // 클래스가 type인 요소의 자식 중 ul 태그의 스타일을 style3으로 변경
            // -> children(매개변수) 사용
            $(".type").children("ul").css(style3);
        
            // 클래스가 wrap인 요소 기준으로
            // li 태그의 스타일을 style 4로 변경

            $(".wrap").children(".type").children("ul").children("li").css(style4);
       
            // 클래스가 wrap인 요소의 후손 중
            // span 요소를 찾아 스타일을 style5로 변경
            // -> find(매개변수) 사용
            $(".wrap").find("span").css(style5);



        });
    </script>

</body>
</html>

반응형