FrontEnd/JQuery

#44. jQuery 기본선택자, 추가적인선택자, 필터링관련선택자, 탐색(순회)메소드_조상, 자식, 동위

열하나요 2023. 9. 1. 15:30

1. 기본선택자

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>기본선택자</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
</head>
<body>

    <h1>기본선택자</h1>

    <!--
        아이디 선택자, 태그 선택자, 클래스 선택자
    -->

    <h3>* 아이디 선택자</h3>
    <p>
        현재 이 HTML문서에서 고유한 아이디 속성값을 가진 요소 단 하나만을 선택할 때 사용
    </p>

    <h1 id="id1">ID1</h1>
    <h2 id="id2">ID2</h2>

    <script>
        $(document).ready(function(){
            // 선택된 요소객체의 속성에 접근해서 값을 변경
            // 순수 자바스크립트 방식
            // document.getElementById('아이디속성값');
            // innerHTML / innerText 대입연산자를 사용해서 값을 대입

            document.getElementById('id1').style.color = 'red';
            document.getElementById('id1').innerHTML = '안녕~';

            // jQuery방식
            // $('#아이디속성값').
            // 선택된 요소객체에 메소드를 활용해서 값을 변경
            $('#id2').css('color', 'pink').html('잘가~');
            // $('#id2').html('잘가~');

            // .html() : innerHTML과 관련된 기능을 수행하는 메소드
        });
    </script>

    <hr>

    <h3>* 태그 선택자</h3>
    <p>
        해당 태그요소를 전부 다 선택하고 싶을 때 사용
    </p>

    <p>Java</p>
    <p>Oracle</p>
    <p>JDBC</p>

    <h5>HTML</h5>
    <h5>CSS</h5>
    <h5>JavaScript</h5>

    <script>
        jQuery(document).ready(function(){
            // 순수 자바스크립트 방식
            // document.getElementsByTagName('태그명'); => 배열 형태
            const p = document.getElementsByTagName('p'); // [p, p, p, p, ...]
            // p.style.color = 'yellow'; p는 배열 => 배열안에 요소로 있는 p요소에게 스타일을 주고싶음
            for(let i = 0; i < p.length; i++){
                p[i].style.color = 'yellow';
            }
            
            // jQuery 방식
            // $('태그명')
            $('h5').css('color', 'blue');

            $('p, h5, #id1').css('background', 'pink');
        });
    </script>

    <hr>

    <h3>* 클래스 선택자</h3>

    <p>
        특정 클래스 속성값을 가진 요소들을 선택할 때 사용
    </p>

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

    <script>
        $(function(){
            // 순수 자바스크립트 방식
            // 대상 => 클래스 속성값이 item인 요소들
            // 글자색 => orangered
            // 클릭 시 => 알림창(메시지 맘대로~)

            const item = document.getElementsByClassName('item');
            for(let i = 0; i < item.length; i++){
                item[i].style.color = 'orangered';
                item[i].onclick = function(){
                    alert('안녕~');
                };
            };

            // jQuery 방식
            // $('.클래스속성값')
            // $('.select').css('backgroundColor', 'lightgray').click(() => {alert('머시기~')});
            $('.select').css('background', 'lightgray');
            $('.select').click(function(){
                console.log('클릭했어~');
            });
            // click() : 클릭 이벤트와 관련된 기능 수행
        });
    </script>

    <!--
        * 요소를 선택하는 방법

        순수 JavaScript 방식                            |   jQuery 방식
        ==============================================================================
        document.getElementById('아이디속성값')         |   $('#아이디속성값')
        document.getElementsByTagName('태그명')         |   $('태그명')
        document.getElementsByClassName('클래스속성값') |   $('.클래스속성값')

        * 선택된 요소의 속성값을 변경하고자 할 때
        ==============================================================================
        순수 JavaScript 방식                            |   jQuery 방식
        ------------------------------------------------------------------------------
        속성에 접근해서 값을 대입                        |  메소드를 호출하는 방식
        Style   |   .style.스타일속성 = '변경할 값';     |  .css('스타일속성', '변경할값');
        Content |   .innerHTML/innerText = '변경할 값'; |   .html('변경할값');
        Event   |   .on이벤트명 = function() {}         |   .이벤트명(function(){});
    -->

</body>
</html>

 

2. 추가적인선택자

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>추가적인 선택자</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>

    <style>
        .pinkStyle{
            background-color: lightpink;
        }
    </style>
</head>
<body>

    <h1>추가적인 선택자</h1>

    <h3>* 자식선택자(>)와 후손선택자( )</h3>

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

        <ul>div의 자식요소1이면서 li의 부모요소이면서 div/h3의 조상요소
            <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>div의 후손이면서 ul의 자식요소5이면서 div/h3의 부모요소
                <div>div/ul의 후손이면서 li의 자식요소1</div>                
                <h3>div/ul의 후손이면서 li의 자식요소2</h3>
            </li>
            <ol>div의 후손이면서 ul의 자식요소6이면서 h3의 부모요소
                <h3>div/ul의 후손이면서 ol의 자식요소1</h3>
            </ol>
        </ul>
        <h3>div의 자식요소2</h3>
        <h3 class="ch">div의 자식요소3</h3>

    </div>

    <script>
        $(function(){
            $('div>h3').css('color', 'blue');
            $('div h3').css('background', 'violet');
            $('li>div').css('color', 'yellowgreen');
            $('ul h3').css('background', 'lightgreen');
            $('div>ul>ol>h3').css('font-size', '15px');
            $('ul>.ch').css('background', 'yellow'); // ul의 자식요소 중에 클래스값이 ch인 요소
            $('li.ch').css('color', 'greenyellow');
        });
    </script>

    <br>
    <hr>

    <h3>* 속성선택자</h3>

    <p>
        선택자[속성] : 특정 속성을 가지고 있는 모든 요소 선택 <br>
        선택자[속성=속성값] : 속성값이 특정값과 "일치"하는 모든 요소 선택 <br>
        선택자[속성~=속성값] : 속성값에 특정값을 "포함"하는 요소 선택(공백기준) <br>
        선택자[속성^=속성값] : 속성값이 특정값으로 "시작"하는 요소 선택 <br>
        선택자[속성$=속성값] : 속성값이 특정값으로 "끝"나는 요소 선택 <br>
        선택자[속성*=속성값] : 속성값에 특정값이 "포함"하는 요소 선택
    </p>

    <br><br>
    <input type="text"> <br>
    <input type="number" class="test test3 test4 test1"> <br>
    <input type="radio"> <br>
    <input type="checkbox"> <br>
    <input type="button" value="button" class="test2"> <br>

    <script>
        /*
        $(function(){
            $('input[class]').css('background', 'lightpink');

            $('input[type=text]').val('안녕'); // value값
            // css() / html()
            // .val() : value속성과 관련된 기능 수행
            $('input[class~=test]').val('1234');

            $('input[type^=ra]').attr('checked', true);
            $('input[type$=box]').attr('checked', true);
            // .attr() : 그 외의 속성들과 관련된 기능 수행

            // 메소드체이닝
            $('input[class*=st2]').css('width', '50px').css('height', '50px').val('버튼');
        })
        */
    </script>

    <hr>

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

    <pre>
        [ 표현법 ]
        $(':type속성값')

        :text, :radio, :number, :checkbox
    </pre>

    텍스트 상자 : <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>
    제출2 : <input type="submit"> <br>

    <script>
        $(function(){

            //$(':text').css('background', 'red');
            // $(':button').css('width', '200px').css('height', '200px').val('왕버튼');
            //$(':button').css({'width' : '200px', 'height' : '200px'}).val('왕버튼');
            // 부여하고자 하는 스타일에 대해 객체 형태로 묶어서 전달하는 것이 가능!

            //$(':checkbox').attr('checked', true);
            // $('div > : checkbox') 이렇게 많이 쓴다궁?
            //$(':file').css('background', 'yellowgreen');

            //$(':radio').css({width : '50px', height : '50px'}).attr('checked', true);

            $(':reset').css({
                background : 'blue',
                color : 'white',
                border : 'none'
            });

            $(':submit').click(function(){
                // alert('경고경고~~📢');

                // 비밀번호 입력란에 작성한 값을 경고창에 띄우기

                // 객체.속성 =          == setter()
                // 객체.속성            == getter()

                // alert($(':password').val());

                // .val() : 인자값 없이 메소드를 호출하면 해당 값을 불러오는 역할
                // setter() / getter() 역할을 동시에 수행
            });

            // mouseenter : 요소의 경게 안으로 들어갈 때
            $(':submit').mouseenter(function(){

                // $(':submit').css('background', 'lightpink'); // 모든 요소가 값을 먹음

                /*
                window.event.target == e.target == this
                this.style.background = 'pink';
                */

                // console.log(this);

                // this.css('background', 'pink');
                // 자바스크립트 요소 객체로 jQuery메소드를 호출할 수 없음

                // $(this).css('background', 'pink');

                // 직접 css() 호출해서 스타일을 부여하는 것이 아니라
                // 클래스 속성값을 추가해서 이미 정의해둔 스타일 입히기

                // jQuery
                // $(this).addClass('추가하고 싶은 클래스 속성값');
                $(this).addClass('pinkStyle');

                // .addClass() : 선택된 요소에 속성값을 추가해주는 메소드

            });

            // mouseout : 요소의 경계 밖으로 나갈 때
            $(':submit').mouseout(function(){
                $(this).removeClass('pinkStyle');
            });

            // mouseenter + mouseout : hover
            $(':submit').hover(function(){
                $(this).addClass('pinkStyle');
            }, function(){
                $(this).removeClass('pinkStyle');
            });
        });
    </script>

    <h3>* 상태선택자</h3>
    <!--
        checked, selected,
        enabled, disabled
    -->

    <h4>checked 상태 선택자(radio, checkbox)</h4>
    <p>
        체크되어있는 입력 양식 태그를 선택 <br>
        $('input:checked')
    </p>

    취미 : 
    <input type="checkbox" value="잠자기" name="hobby"> 잠자기
    <input type="checkbox" value="코딩" name="hobby"> 코딩
    <input type="checkbox" value="맛집탐방" name="hobby"> 맛집탐방

    <br>

    <button id="btn1">너 취미가 뭐니??</button>

    <script>
        
        $(function(){
            // 버튼 클릭 시 현재 checked된 요소만 선택해서 스타일부여
            $('#btn1').click(function(){

                // $(':checked').css({width : '50px', height : '50px'});

                // '자바스크립트' 방식으로
                // 버튼 클릭 시 현재 checked된 요소만 선택해서 alert창으로
                // 당신의 취미는 XX XX XX이군요? 형식으로 출력

                /*
                let arr = document.getElementsByName('hobby');
                let str = '';

                for(let i = 0; i < arr.length; i++){
                    if(arr[i].checked){
                        str += arr[i].value + ' ';
                    }
                };
                alert(str);
                */

                str = '';
                $('input[name=hobby]').filter(':checked').each(function(){
                    str += $(this).val() + ' ';
                });
                alert(str);
            });

        });
        
        //이건 왜안디야.. 함수호출..
        // var arr = document.getElementsByName('hobby')
        // document.getElementById('btn1').click = function(){

        //     var hobbies = '';
        //     for(let i = 0; i < arr.length; i++){
        //         if(arr[i].checked){
        //             hobbies += arr[i].value;
        //         };
        //     };
        //     alert(hobbies);
        // };
    </script>

    <h4>selected 상태 선택자(select>option)</h4>

    <p>
        option 요소 객체 중 선택된(selected) 태그를 선택 <br>
        $('option:selected')
    </p>

    지역
    <select name="location">
        <option value="X">선택안함</option>
        <option value="GW">강원도</option>
        <option value="BS">부산</option>
    </select>

    <button id="btn2">확인</button>
    <br>

    선택한 지역 : <label id="result">없음</label>

    <script>
        $(function(){
            $('#btn2').click(function(){
                
                // console.log($('option:selected').value());
                console.log($('option:selected').html());

                // $('#result').html($('option:selected').html());

                document.getElementById('result').innerHTML = $('option:selected').html();
            });
        });
    </script>

    <hr>

    <h4> - enabled, disabled상태(input, button, textarea...)</h4>

    <p>
        활성화/비활성화 상태 <br>
        :enabled <br>
        :disabled <br>
    </p>

    <div id="wrap">
        활성화 텍스트 상자 : <input type="text"> <br>
        비활성화 텍스트 상자 : <input type="text" disabled> <br>

        활성화 버튼 : <input type="button"> <br>
        비활성화 버튼 : <input type="button" disabled> <br>
    </div>

    <script>
        $(function(){
            $('#wrap>:enabled').css('background', 'yellowgreen');
            $('#wrap>:disabled').css('background', 'greenyellow');
        })
    </script>

</body>
</html>

 

3. 필터링관련선택자

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>필터링관련선택자</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>

</head>
<body>

    <h1>필터링 관련 선택자 및 메소드</h1>

    <h3>* 필터 관련 선택자 </h3>

    <table border="1">
        <tr>
            <th>이름</th>
            <th>MBTI</th>
            <th>혈액형</th>
        </tr>
        <tr>
            <td>이땡철</td>
            <td>HTML</td>
            <td>AB형</td>
        </tr>
        <tr>
            <td>유유히</td>
            <td>JDBC</td>
            <td>B형</td>
        </tr>
        <tr>
            <td>개똥이</td>
            <td>AJAX</td>
            <td>O형</td>
        </tr>
        <tr>
            <td colspan="2">총 인원</td>
            <td>3명</td>
        </tr>
    </table>

    <script>
        $(function(){
            // :first, :last, :even, :odd
            $('tr:first').css('background', 'black').css('color', 'white'); // first 첫 번째 요소를 의미
            $('tr:last').css({background : 'orangered', color : 'white'}); // last 마시막요소를 의미
            $('tr:even').css('background', 'gray'); // even 짝수번째 요소를 의미
            $('tr:odd').css('background', 'yellowgreen'); // odd 홀수번째 요소를 의미
            // even하고 odd는 0부터 시작
        })
    </script>

    <h3>* 필터 관련 메소드</h3>
    <p>
        기준이 되는 요소 중에서 특정 요소만을 걸러서 선택해주는 메소드 <br>
        first(), last(), filter(), not(), *************** eq()
    </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>
        $(function(){
            // .first() : 기준중에서 가장 첫 번째를 선택
            $('h4').first().css('font-size', '20px');
            // .last() : 기준중에서 가장 마지막을 선택
            $('h4').last().css('font-size', '50px');
            // .filter('선택자') : 기준 중에서 해당 선택자만 선택
            $('h4').filter('.test').html('ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ');

            // .not('선택자') : 기준 중에서 해당 선택자가 아닌것만 선택 ***
            $('h4').not('.test').css('color', 'skyblue');

            // .eq(위치) : 0부터 시작, 몇 번째 요소 선택 *****
            $('h4').eq(0).text('<b>eq(0) 선택됨</b>');
            // text() : 선택된 요소의 innerText와 관련된 기능을 수행

        });
    </script>

</body>
</html>

4. 탐색(순회)메소드_조상

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>탐색(순회)메소드_조상</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <style>
        .wrap, .wrap *{
            display : block;
            border : 1px solid skyblue;
            margin : 15px;
            padding : 5px;
            color : blue;
        }
    </style>
</head>
<body>

    <h1>탐색 순회 메소드(Travering)</h1>

    <h3>
        * Ancestors(조상) 메소드 : 기준이 되는 요소의 상위요소들을 선택할 수 있는 메소드
    </h3>

    <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>
    
    <p>
        <h4>- $('선택자').parent()</h4>
        선택된 요소를 기준으로 바로 위의 상위 부모요소 하나만을 선택

        <h4>- $('선택자').parents()</h4>
        선택된 요소를 기준으로 모든 상위요소를 선택

        <h4>- $('선택자').parents('선택자')</h4>
        선택된 요소를 기준으로 모든 상위요소들 중에서 내가 인자값으로 전달한 값과 일치하는 상위요소들만 선택

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

    <script>
        $(function(){

            // parent()
            $('span').parent().css({color:'palegreen', border:'2px solid palegreen'});
            
            // parents()
            $('span').parents().css('color', 'coral');

            // parents('선택자')
            $('span').parents('div').css('border', '2px dashed orange');

            // parentsUntil('선택자')
            $('span').parentsUntil('div').css('color', 'forestgreen');

            $('span').parent().parent().css('color', 'lightpink');
        })
    </script>
    
</body>
</html>

 

 

5. 탐색(순회)메소드_자식

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>탐색(순회)메소드_자식  찾아~~~</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <style>
        .wrap, .wrap *{
            display : block;
            border : 1px solid skyblue;
            margin : 15px;
            padding : 5px;
            color : blue;
        }
    </style>
</head>
<body>

    <h1>탐색(순회)메소드</h1>

    <h3>
        * Descendents(자식) 메소드 : 기준이 되는 요소의 하위요소를 선택할 수 있는 메소드
    </h3>

    <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>
    

    <p>
        <h4>- $('선택자').children()</h4>
        선택된 요소를 기준으로 모든 자식(바로 하위) 요소들을 선택

        <h4>- $('선택자').children('선택자')</h4>
        선택된 요소를 기준으로 모든 자식요소들 중에서 제시한 값과 일치하는 요소들만 선택

        <h4>- $('선택자').find('선택자')</h4>
        선택된 요소를 기준으로 모든 후손요소들 중에서 제시한 값과 일치하는 요소들만 선택
    </p>

    <script>
        $(function(){

            // 스타일 객체
            const style1 = {
                color : 'gold',
                border : '2px solid gold'
            };

            const style2 = {
                color : 'silver',
                border : '2px solid silver'
            };

            const style3 = {
                color : 'cornflowerblue',
                border : '2px solid cornflowerblue'
            };

            const style4 = {
                color : 'rgb(0, 255, 167)',
                border : '2px solid rgb(0, 255, 167)' 
            };

            const style5 = {
                color : 'aqua',
                border : '2px solid aqua'
            };

            // children()
            $('.wrap').children().css(style1);
            $('.wrap').children().children().css(style2); // 자식요소의 자식요소라는 뜻


            // children('선택자')
            $('.wrap').children().children('ul').css(style3);

            // find('선택자')
            $('.wrap').find('span').css(style2);
            $('.wrap').find('li').css(style5);


        })
    </script>


</body>
</html>

 

6. 탐색(순회)메소드_동위

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>동위</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <style>
        .wrap, .wrap *{
            display : block;
            border : 1px solid violet;
            margin : 15px;
            padding : 5px;
            color : gray;
        }
    </style>
</head>
<body>

    <h1>탐색(순회) 메소드</h1>

    <h3>
        * SideWays(동위)메소드 : 같은 레벨에 있는 요소들을 선택할 수 있는 메소드
    </h3>

    <!--
        siblings(), siblings('선택자'),
        next(), nextAll(), nextUntil(),
        prev(), prevAll(), prevUntil()
    -->

    <div class="wrap">
        <p>p</p>
        <div>div</div>
        <span>span</span>
        <h2>h2</h2> <!-- 기준점 -->
        <h3>h3</h3>
        <p>p</p>
    </div>

    <p>
        <h4>- $('선택자').siblings()</h4>
        선택된 요소를 기준으로 같은 레벨에 있는 모든 요소들을 선택

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

        <h4>- $('선택자').next()</h4>
        선택된 요소를 기준으로 같은 레벨에 있는 모든 요소들 중에서 바로 다음 요소 하나만 선택

        <h4>- $('선택자').nextAll()</h4>
        선택된 요소를 기준으로 같은 레벨에 있는 모든 요소들 중에서 내 뒤에 있는 요소들을 모두 선택

        <h4>- $('선택자').nextUntil('선택자')</h4>
        선택된 요소를 기준으로 같은 레벨에 있는 모든 요소들 중에서 
        내 뒤에있는 요소부터 제시한 값과 일치하는 요소를 만나기 전까지만 선택

        <h4>- $('선택자').prev()</h4>
        선택된 요소를 기준으로 같은 레벨에 있는 모든 요소들 중에서 내 바로 이전 요소 딱 하나만을 선택

        <h4>- $('선택자').prevAll()</h4>
        선택된 요소를 기준으로 같은 레벨에 있는 모든 요소들 중에서 바로 이전 요소들 전부 선택

        <h4>- $('선택자').prevUntil()</h4>
        선택된 요소를 기준으로 같은 레벨에 있는 모든 요소들 중에서 
        내 앞에 있는 요소부터 제시한 값과 일치하는 요소를 만나기 전까지만 선택
    </p>

    <script>
        $(function(){

            // 스타일 객체
            const style1 = {
            color : 'gold',
            border : '2px solid gold'
            };

            const style2 = {
                color : 'silver',
                border : '2px solid silver'
            };

            const style3 = {
                color : 'cornflowerblue',
                border : '2px solid cornflowerblue'
            };

            const style4 = {
                color : 'rgb(0, 255, 167)',
                border : '2px solid rgb(0, 255, 167)' 
            };

            const style5 = {
                color : 'aqua',
                border : '2px solid aqua'
            };

            // siblings => 본인은 제외
            $('h2').siblings().css(style1);
            $('h2').siblings('p').css(style2);

            // next계열
            $('h2').next().css(style3);
            $('h2').nextAll().css('font-size', '3em');
            $('h2').nextUntil('p').css('color', 'orangered');

            // prev계열
            $('h2').prev().css('background', 'orangered');
            $('h2').prevAll().css('color', 'black');
            $('h2').prevUntil('p').css('border', '5px dached magenta');

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

 

7. content영역관련 메소드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>content영역관련메소드</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>

</head>
<body>

    <h1>content 영역관련 메소드</h1>

    <h3>************ html('문구') : innerHTML 속성과 관련된 메소드</h3>

    <p>
        선택된 요소의 content영역(여는태그와 닫는태그 사이)을 리턴해주거나
        또는 변경해주는 메소드 <br>

        - $('선택자').html() : 선택된 요소의 content영역의 값을 반환해줌 <br>
        - $('선택자').html('문구') : 선택된 요소의 content영역의 값을 해당 문구로 바꿔줌 <br>
        => 이 때 HTML태그를 인식 O
    </p>

    <h1 id="test1">
        <a>네이버로</a>
    </h1>

    <h1 id="test2" style="border : 1px solid black">

    </h1>

    <script>
        $(function(){

            // 자바스크립트 방식
            // let tmp = document.getElementById('test1').innerHTML;
            // console.log(tmp);
            

            // href속성 추가(속성값으로는 http://www.naver.com)

            // let arr = document.getElementsByTagName('a');
            // console.log(arr[0]);
            // arr[0].href = 'http://www.naver.com';

            // document.getElementById('test2').innerHTML = document.getElementById('test1').innerHTML;

            // 제이쿼리 방식
            let tmp = $('#test1').html();
            console.log(tmp);

            $('#test2').html(tmp);

            // href속성 추가
            $('#test2').children().attr('href', 'http://www.naver.com');



        })
    </script>



    
</body>
</html>