개발새발 블로그

[jQuery] 요소 탐색(순회)메소드 동위

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>요소탐색(순회)메소드 동위</title>
    <script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
    <style>
        .wrap, .wrap * {
            border: 1px solid lightgray;
            color: gray;
            display: block;
            padding: 5px;
            margin: 15px;
        }
    </style>
</head>
<body>
    <h1>탐색(순회) 메서드</h1>
    <h3>* 동위 메서드 : 같은 레벨에 있는 요소들을 선택할 수 있는 메서드</h3>
    <p>
        <h4>- $('선택자').siblings()</h4>
        선택된 요소와 같은 레벨에 있는 모든 요소들 선택

        <h4>- $('선택자').siblings('선택자')</h4>
        선택된 요소와 같은 레벨에 있는 모든 요소들 중 제시한 값과 일치하는 요소들만 선택

        <h4>- $('선택자').next|prev()</h4>
        선택된 요소와 같은 레벨 요소들 중 바로 다음요소|이전요소 하나만 선택

        <h4>- $('선택자').nextAll|prevAll()</h4>
        선택된 요소와 같은 레벨 요소들 중 모든 다음요소|이전요소들 선택

        <h4>- $('선택자').nextUntil()</h4>
        선택된 요소와 같은 레벨 요소들 중 제시한 값과 일치하는 요소 까지만 선택
    </p>

    <div class="wrap">
        <p>p</p>
        <span>span</span>
        <h2>h2</h2>
        <h3>h3</h3>
        <p>p</p>
    </div>

    <script>
        $(() => {
            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 = {backgroundColor:'aqua', color:'orange'};

            $('h2').siblings().css(style1);
            $('h2').siblings('p').css(style2);

            $('h2').next().css(style3);
            $('h2').nextAll().css(style4);
            $('h2').nextUntil('p').css('font-size', '3em');

            $('h2').prev().css('backgroundColor', 'pink');
            $('h2').prevAll().css(style4);
            $('h2').prevUntil('p').css('border', 'dotted');
        })
    </script>
</body>
</html>

[jQuery] 요소 탐색(순회)메소드 자손 후손

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>요소탐색(순회)메소드자손후손</title>
    <script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
    <style>
        .wrap, .wrap * {
            border: 1px solid lightgray;
            color: gray;
            display: block;
            padding: 5px;
            margin: 15px;
        }
    </style>
</head>
<body>
    <h1>탐색(순회) 메서드</h1>
    <h3>* 자손 메서드 : 기준이 되는 요소의 하위요소들을 선택할 수 있는 메서드</h3>
    <p>
        <h4>- $('선택자').children()</h4>
        선택된 요소의 자손(바로 하위)요소들 선택

        <h4>- $('선택자').children('선택자')</h4>
        선택된 요소의 모든 자손들 중 제시한 값과 일치하는 요소들만 선택

        <h4>- $('선택자').find('선택자')</h4>
        선택된 요소의 모든 후손(하위요소들 전체)들 중 제시한 값과 일치하는 요소들만 선택
    </p>

    <div class="wrap">
        <div>div(증조할머니)
            <ul>ul(할머니)
                <li>li(엄마)
                    <span>span(나)</span>
                </li>
            </ul>
        </div>
        <div>div(할아버지)
            <p>p(아빠)
                <span>span(나)</span>
            </p>
        </div>
    </div>

    <script>
        $(() => {
            // 앞으로 부여할 스타일 객체를 만들어 변수에 저장
            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').find('li').css(style4);
            $('.wrap').find('span').css(style5);
        })
    </script>

</body>
</html>

[jQuery] 요소 탐색(순회)메소드 조상

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>요소탐색(순회)메소드 조상</title>
    <script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
    <style>
        .wrap, .wrap * {
            border: 1px solid lightgray;
            color: gray;
            display: block;
            padding: 5px;
            margin: 15px;
        }
    </style>
</head>
<body>
    <h1>탐색(순회) 메서드</h1>
    <h3>* 조상 메서드 : 기준이 되는 요소의 상위요소들을 선택할 수 있는 메서드</h3>
    <p>
        <h4>- $('선택자').parent()</h4>
        선택된 요소의 바로 위 상위(부모)요소 하나만 선택

        <h4>- $('선택자').parents()</h4>
        선택된 요소의 모든 상위요소들 선택

        <h4>- $('선택자').parents('선택자')</h4>
        선택된 요소의 모든 상위요소들 중에서 제시한 값과 일치하는 상위요소들만 선택

        <h4>- $('선택자').parentsUntil('선택자')</h4>
        선택된 요소부터 제시한 값까지의 모든 상위요소들 선택
    </p>

    <div class="wrap">
        <div>div(증조할머니)
            <ul>ul(할머니)
                <li>li(엄마)
                    <span>span(나)</span>
                </li>
            </ul>
        </div>
        <div>div(할아버지)
            <p>p(아빠)
                <span>span(나)</span>
            </p>
        </div>
    </div>

    <script>
        $(() => {
            $('span').parent().css({color: 'red', border: '2px solid red'});
            $('li').parents().css('color', 'blue');
            $('li').parents('div').css('border', '2px dashed magenta');
            
            // .parentsUntil('선택자') : 선택자 이전까지만 바뀜
            $('span').parentsUntil('div').css('color', 'pink');
        })
    </script>

</body>
</html>

[jQuery] 요소선택(필터링 선택자)

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>요소선택(필터링 선택자)</title>
    <script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
</head>
<body>
    <h1>* 필터링 관련 선택자</h1>

    <table border="1" style="text-align: center;">
        <tr>
            <th>이름</th>
            <td>혈액형</td>
            <td>거주지</td>
        </tr>
        <tr>
            <td>이영희</td>
            <td>B형</td>
            <td>경기도</td>
        </tr>
        <tr>
            <td>김철수</td>
            <td>O형</td>
            <td>경기도</td>
        </tr>
        <tr>
            <td>이윤성</td>
            <td>A형</td>
            <td>대전</td>
        </tr>
        <tr>
            <td colspan="2">총인원</td>
            <td>3명</td>
        </tr>
    </table>

    <script>
        $(() => {
            $('tr:even').css('backgroundColor', 'lightgray');
            $('tr:odd').css('backgroundColor', 'lightcyan');
            $('tr:first').css({backgroundColor: 'black', color: 'white'});
            $('tr:last').css({backgroundColor: 'dimgray', color: 'white'});
        })
    </script>

    <h3>* 필터링 관련 메소드</h3>
    <p>
        기준이 되는 요소 중에서 특정 요소만을 걸러서 선택해주는 메소드<br>
        first(), last(), filter(), eq(), not()
    </p>
    
    <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>
        $(() => {
            $('h4').first().css('font-size', '20px');
            $('h4').last().css('font-size', '30px');

            $('h4').filter('.test').html('<i>필터메서드로 바꿈</i>');
            $('h4').not('.test').css('color', 'red');           // 제외하고

            // innerHTML == .html()
            // innerText == .text()
            $('h4').eq(2).text('<i>eq로 선택됨</i>');
        })
    </script>
</body>
</html>

[jQuery] 요소 선택(기본 이 외 선택자)

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>요소선택(기본이외선택자)</title>
    <script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
    <style>
        div {
            border: 1px solid;
        }
        .test {
            background-color: aqua;
        }
    </style>
</head>
<body>
    <h1>기본 이외의 선택자</h1>
    <h3>* 자손선택자(>)와 후손선택자</h3>

    <div>
        <ul>자손1
            <li>div의 후손이면서 ul의 자손1</li>
            <li>div의 후손이면서 ul의 자손2</li>
            <li class="ch">div의 후손이면서 ul의 자손3</li>
            <li class="ch">div의 후손이면서 ul의 자손4</li>
            <li><h3>div와 ul의 후손이면서 li의 자손</h3></li>
        </ul>
        <h3>자손2</h3>
        <h3 class="ch">자손3</h3>
    </div>

    <script>
        $(() => {
            $('div>h3').css('color', 'lightblue');
            $('div h3').css('backgroundColor', 'violet');

            // $('ul h3').css('color', 'red');
            // $('li>h3').css('color', 'red');
            $('ul>li>h3').css('color', 'red');

            // $('.ch').css('backgroundColor', 'yellow');

            // $('ul>.ch').css('backgroundColor', 'yellow');
            // $('ul>.ch').css('color', 'pink');
            /*
            $('ul>.ch').css('backgroundColor', 'yellow')
                       .css('color', 'pink');
            */
            $('ul>.ch').css({backgroundColor:'yellow', color:'pink'});      // 객체
        })
    </script>

    <hr>

    <h3>* 속성선택자</h3>
    <p>
        선택자[속성] : 특정 속성을 가지고 있는 모든 요소 선택<br>
        선택자[속성=특정값] : 속성값이 특정값과 "일치"하는 모든 요소 선택<br>
        선택자[속성~=특정값] : 속성값이 특정값을 "단어로써 포함"하는 모든 요소 선택<br>
        선택자[속성^=특정값] : 속성값이 특정값으로 "시작"하는 모든 요소 선택<br>
        선택자[속성$=특정값] : 속성값이 특정값으로 "끝"나는 모든 요소 선택<br>
        선택자[속성*=특정값] : 속성값이 특정값이 "포함"되어 있는 모든 요소 선택<br>
    </p>
    <input type="text"><br>
    <input type="number" class="test test1"><br>
    <input type="radio"><br>
    <input type="checkbox"><br>
    <input type="button" value="button" class="test2">
    
    <!--
    <script>
        $(() => {
            /*
            .val('속성값') : 선택한 요소에 value 속성 추가(기존에 있으면 속성값 바꾸기)
            .attr('속성명', '속성값') : 선택한 요소에 속성을 추가
            */
            $('input[class]').css('backgroundColor', 'yellowgreen');
            $('input[type=text]').val('change value');
            $('input[class~=test]').val('12345');
            $('input[type^=ra]').attr('checked', true);
            $('input[type$=box]').attr('checked', true);

            // $('input[class*=st2]').css({width: '100px', height:'50px'});
            // $('input[class*=st2]').val('왕버튼');
            $('input[class*=st2]').css({width: '100px', height:'50px'})
                                  .val('왕버튼');
        })
    </script>
    -->

    <h3>* 입력 양식 선택자(input태그의 type속성에 따라 요소 선택)</h3>

    텍스트상자 : <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>
        $(() => {
            $(':text').css('backgroundColor', 'red');
            $(':button').css({width:'60px', height:'20px'})
                        .val('버튼');
            $(':checkbox').attr('checked', true);
            $(':file').css('backgroundColor', 'green');
            $(':password').css('backgroundColor', 'yellow');
            $(':radio').attr('checked', true)
                       .css({width:'50px', height:'50px'});
            // 초기화버튼 : 배경색 파란색, 글자색 흰색, 테두리 없애기, 문구를 취소로 변경
            $(':reset').css({backgroundColor:'blue', color:'white', border:'none'})
                       .val('취소');
            // 제출버튼 : 클릭시 alert('안녕') 실행
            $(':submit').click(function() {
                // alert('안녕')
                alert($(':password').val())     // 비밀번호 값 가져오기
            });

            // mouseenter
            $(':submit').mouseenter(function() {
                $(this).css('color', 'red');
                $(this).addClass('test');
            });

            // mouseout
            $(':submit').mouseout(function() {
                $(this).css('color', '');       // 원래대로 값
                $(this).removeClass('test');
            });
        })
    </script>
    -->

    <h3>* 상태(checked, selected, disabled, enabled)</h3>

    <h4>- checked상태 선택자(radio, checkbox)</h4>

    취미 : 
    <input type="checkbox" name="hobby" value="game">게임
    <input type="checkbox" name="hobby" value="movie">영화
    <input type="checkbox" name="hobby" value="music">음악
    <br>
    <button type="button" id="btn">실행확인</button>

    <script>
        $(() => {
            /*
            $('#btn').click(function() {
                $('input:checked').css({width:'50px', height:'50px'});      // 체크되어 있는 것만
            });
            */

            $(':checkbox').change(function() {
                console.log('변경됨');
                console.log($(this).prop('checked'));

                if($(this).prop('checked')) {
                    $(this).css({width:'50px', height:'50px'});
                } else {
                    $(this).css({width:'', height:''});
                }
            });
        })
    </script>

    <h4>- selected상태 선택자(select>option)</h4>
    국적 :
    <select name="national">
        <option value="x">선택안함</option>
        <option value="ko">한국</option>
        <option value="us">미국</option>
        <option value="uk">영국</option>
    </select>
    <button type="button" onclick="test();">확인</button>
    <br>

    선택한 나라 : <span id="result"></span>

    <script>
        function test() {
            // 현재 선택된 option요소 선택
            console.log($('option:selected').val());
            console.log($('option:selected').html());       // html 가지고오기

            $('#result').html($('option:selected').html());
        }
    </script>

    <h4>- disabled, enabled상태 선택자(input요소들, button 등)</h4>

    <button type="button">활성화 버튼</button>
    <button type="button" disabled>비활성화 버튼</button>

    <script>
        $(() => {
            $('button:enabled').css('color', 'hotpink');
            $('button:disabled').css('color', 'black');
        })
    </script>
</body>
</html>

[jQuery] 요소선택(기본선택자)

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>요소선택(기본선택자)</title>
    <script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
</head>
<body>
    <h1>기본선택자를 이용한 요소 선택</h1>
    <h3>* 아이디 선택</h3>
    <p>고유한 아이디값을 가진 요소 '하나만'선택할 때 사용</p>

    <h2 id="id1">아이디 테스트</h2>

    <script>
        $(() => {
            // 자바스크립트에서 사용
            // document.getElementById('id1').style.color = 'red';
            // document.getElementById('id1').innerHTML = '글자변경'

            // jQuery 사용
            // .html() : 선택된 요소의 innerHTML과 관련된 기능을 수행하는 메서드
            $('#id1').css('color', 'green');
            $('#id1').html('글자변경');

            // console.log(document.getElementById('id1'));
            console.log($('#id1'));
        })
    </script>

    <hr>

    <h3>* 클래스 선택자</h3>
    <p>특정 클래스 속성을 가진 요소들을 선택하고자 할 때</p>

    <h1 class="item">Class1</h1>
    <h1 class="item select">Class2</h1>
    <h1 class="item select">Class3</h1>

    <script>
        $(() => {
            // 자바스크립트
            const items = document.getElementsByClassName('item');
            for(let i=0; i<items.length; i++) {
                items[i].style.color = 'orange';
                items[i].onclick = function() {
                    console.log('클릭됨');
                }
            }

            // jQuery
            $('.select').css('backgroundColor', 'pink');
            $('.select').click(function() {
                alert('클릭됨');
            })
        })
    </script>

    <!--
        * 요소 선택하는 방법
         순수 자바스크립트 방식                              | jQuery
        ====================================================================
         document.getElementById('아이디명')               | $('#아이디명')
         document.getElementsByClassName('클래스명')       | $('.클래스명')
         document.getElementsByTagName('태그명')           | $('태그명')
        
         
        * 선택된 요소에서 속성값을 변경하고자 할 때

         순수 자바스크립트 방식                              | jQuery
        ----------------------------------------------------------------------------------
         선택된 요소 객체의 직접 속성에 접근해서 사용         | 선택된 요소에 메서드 이용
        ===================================================================================
         스타일 | .style.스타일속성 = '변경할 값'            | .css('스타일 속성', '변경할 값')
         내용   | .innerHTML = '변경할 값'                  | .html('변경할 값')
         이벤트 | .on이벤트명 = function(){}                | .이벤트명(function(){})
    -->
</body>
</html>