본문 바로가기

클라이언트/JavaScript
[자바스크립트(JavaScript)] DOM

// DOM, Document Object Model > 돔
    - BOM을 개선한 모델
    - 현재까지 계속 사용(주력)
    - BOM 기반 + 기능 추가 
    - DOM > BOM 확장 > DOM의 모든 기능을 BOM의 document 내부에 구현해놨다.
    - 모든 태그를 인식 > 모든 태그 조작 가능
    - name, id, class 모두 인식할 수 있다.(name 비권장)
    - 버전이 있다. (DOM Level 1 > DOM Level 2 > DOM Level 3)
        ~ DOM Level 0: BOM을 일컫기도 한다.

    - 태그 검색
        1. id 검색 > document.getElementById('id')
        2. class 검색 > document.getElementByClassName('id')
        3. name 검색 > document.getElementByName('id')
        4. 태그명 검색 > document.getElementByTagName('id')
        5. CSS 선택자 검색 > document.querySelector('selector')
                                            document.querySelectorAll('selector')


    - DOM 트리 구성 요소(노드): 태그뿐만 아니라 다른 요소들도 포함
        1. 태그(1)
        2. 속성(2)
        3. PCDATA(3)
        4. 주석(8)
        5. 선언문(13)

    - DOM 트리 구성 노드의 프로퍼티 
        1. nodeType > 해당 노드가 어떤 형식인지 > 열거형(숫자)
        2. nodeName > 태그(태그명), 속성(속성명), PCDATA(#text)
        3. nodeValue > 태그(null), 속성(속성값), PCDATA(문자열)- id 검색


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        input {
            display: block;
            margin: 10px;
        }
    </style>
</head>
<body>

    <h1>DOM</h1>     

    <form name="form1">
        <h2 id="title">Control</h2>
        <div>
            <input type="text" name="txt1" id="txt1" class="txt">
            <input type="text" name="txt2" id="txt2" class="txt">
            <input type="text" name="txt3" id="txt3" class="txt">
            <input type="button" value="확인" name="btn1" id="btn1">
        </div>
    </form>

    <script>
        
        /* 1.id 검색 */

        //BOM
        window.document.form1.txt1.value = 'BOM';

        //DOM
        document.getElementById('txt2').value = 'DOM';
        console.log(document.form1.txt1 == document.getElementById('txt1'));

    </script>

</body>
</html>

- class 검색

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        input {
            display: block;
            margin: 10px;
        }
    </style>
</head>
<body>

    <h1>DOM</h1>     

    <form name="form1">
        <h2 id="title">Control</h2>
        <div>
            <input type="text" name="txt1" id="txt1" class="txt">
            <input type="text" name="txt2" id="txt2" class="txt">
            <input type="text" name="txt3" id="txt3" class="txt">
            <input type="button" value="확인" name="btn1" id="btn1">
        </div>
    </form>

    <script>

        /* 2. class 검색*/
        
        //DOM
        let txt = document.getElementsByClassName('txt');
        console.log((txt.length));

        for (let i = 0; i < txt.length; i++) {
            txt[i].value = i;
        }
        

    </script>

</body>
</html>

- name 검색, 태그명 검색

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        input {
            display: block;
            margin: 10px;
        }
    </style>
</head>
<body>

    <h1>DOM</h1>     

    <form name="form1">
        <h2 id="title">Control</h2>
        <div>
            <input type="text" name="txt1" id="txt1" class="txt">
            <input type="text" name="txt2" id="txt2" class="txt">
            <input type="text" name="txt3" id="txt3" class="txt">
            <input type="button" value="확인" name="btn1" id="btn1">
        </div>
    </form>

    <script>               

        /* 3. name 검색 */
        document.getElementsByName('txt1')[0].value = '홍길동'
        
        
        /* 4. 태그명 검색 */
        let input = document.getElementsByTagName('input');

        for (let i = 1; i < input.length; i++) {
            input[i].value = i;
        }

    </script>

</body>
</html>

- 태그명 검색

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>        
        
        #tbl1 {
            border: 1px solid gray;
            border-collapse: collapse;
        }

        #tbl1 td {
            border: 1px solid gray;
            width: 126px;
            height: 126px;
        }

        #tbl1 img {
            display: block;
        }

    </style>
</head>
<body>
    <table id="tbl1">
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </table>

    <script>

        let index = 0;
        const list = document.getElementsByTagName('td');

        list[index].bgColor = 'gold';

        window.onkeydown = function() {
            
            // list[index].bgColor = 'transparent';
            for (let i = 0; i < list.length; i++) {
                list[i].bgColor = 'transparent';
            }

            if(event.keyCode == 39) {
                //우측 방향키
                index++;

                //끝
                if(index >= list.length) {
                    // alert('우측 끝입니다.')
                    // index--;
                    index = 0;
                }

            } else if(event.keyCode == 37) {
                //좌측 방향키
                index--;
                if(index < 0) {
                    // alert('좌측 끝입니다.')
                    // index++;
                    index = list.length - 1;
                }
            }

            list[index].bgColor = 'gold';
        }
    </script>
</body>
</html>

- css 선택자 검색

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        input {
            display: block;
            margin: 10px;
        }
    </style>
</head>
<body>

    <h1>DOM</h1>     

    <form name="form1">
        <h2 id="title">Control</h2>
        <div>
            <input type="text" name="txt1" id="txt1" class="txt">
            <input type="text" name="txt2" id="txt2" class="txt">
            <input type="text" name="txt3" id="txt3" class="txt">
            <input type="button" value="확인" name="btn1" id="btn1">
        </div>
    </form>

    <script>
    
        /* 5. CSS 선택자 검색 */
        document.querySelector('#txt1').value = 'CSS'
        document.querySelectorAll('.txt')[1].value = 'CSS All'


    </script>

</body>
</html>

// PCDATA 조작
        - 콘텐츠 조작 > 시작 태그와 끝 태그 사이의 내용물 조작

        1. innerText
            - 시작 태그와 끝 태그 사이의 문자열 읽기/쓰기 프로퍼티
            - 비표준(MS)

        2. innerHTML
            - 시작 태그와 끝 태그 사이의 문자열과 태그 읽기/쓰기 프로퍼티
            - 문자열 + 태그
            - 태그를 인식한다.

        3. outerText
            - 사용 안 함

        4. outerHTML
            - 사용 안 함

        5. textContent
            - 시작 태그와 끝 태그 사이의 문자열 읽기/쓰기 프로퍼티
            - 표준


- innerHTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        fieldset { border: 1px solid #777; width: 200p; }
        fieldset > * {display: block; margin-bottom: 10px;}

        #tbl1 {
            border: 1px solid gray;
            border-collapse: collapse;
            margin-top: 20px;
        }

        #tbl1 td {
            border: 1px solid gray;
            width: 50px;
            height: 50px;
            text-align: center;
        }
    </style>
</head>
<body>

    <h1>테이블 생성하기</h1> 

    <fieldset>
        <legend>행 x 열</legend>
        <label>행: <select id="selrow"></select></label>
        <label>열: <select id="selcolumn"></select></label>
        <input type="button" value="만들기" id="btncreate">
    </fieldset>

    <table id="tbl1"></table>

    <script>
        const selrow = document.getElementById('selrow');
        const selcolumn = document.getElementById('selcolumn');
        const btncreate = document.getElementById('btncreate');

        btncreate.onclick = function() {
            let temp =''; //누적변수

            for(let i = 0; i < selrow.value; i++) {//행 생성<tr>

                temp += '<tr>';

                for (let j = 0; j < selcolumn.value; j++) { //열 생성<td>
                    temp += '<td>';
                    temp += i + ',' + j;
                    temp += '</td>';
                }

                temp += '</tr>';

            }

            tbl1.innerHTML = temp;
        };

    </script>

</body>
</html>

- property

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            border: 1px solid black;
            padding: 10px;
            margin: 10px;
        }
        #me {
            outline: 5px solid black;
        }
        .check {
            background-color: gold;
        }
    </style>
</head>
<body>

    <h1>Axis</h1> 

    <input type="button" value="버튼" id="btn">
    <hr>

    <div>
        할아버지
        <div>
            큰아버지
            <div>사촌</div>
        </div>
        <div>
            아버지
            <div>
                큰형
                <div>조카</div>
            </div>
            <div>
                작은형
            </div>
            <div id="me">
                나
                <div>큰애</div>
                <div>
                    둘째
                    <div>손자</div>
                </div>
                <div>막내</div>
            </div>
            <div>
                동생
            </div>
            <div>
                막내동생
                <div>조카</div>
            </div>
        </div>
        <div>
            작은아버지
            <div>사촌</div>
        </div>
    </div>

    <script>
        
        document.getElementById('btn').onclick = function() {
            
            const me = document.getElementById('me');

            for(let i = 0; i < me.childNodes.length; i++) {
                console.log(me.childNodes[i].nodeType
                            , me.childNodes[i].nodeName
                            , me.childNodes[i].nodevalue);
            }

        }
    </script>

</body>
</html>