TIL 0409

먼지·2024년 4월 9일

Today I Learned

목록 보기
37/89
post-thumbnail

클래스를 이용한 문서 객체 탐색

    <title>클래스를 이용한 문서 객체 탐색</title>
    <script>
        window.onload = function() {
            //태그의 class 속성이 지정한 class명과 일치하는 문서 객체를 배열로 반환
            const foo = document.getElementsByClassName('matched');
            let output = '[class명이 matched인 모든 태그의 text 출력]\n';
            for(let i = 0; i<foo.length; i++){
                output += foo[i].innerHTML + '\n';
            }
            alert(output);

            //id가 foo인 p 태그
            const foo2 = document.getElementById('foo');
            //id가 foo인 p태그의 하위 태그 중 class 명이  matched인 태그들을 반환
            const fooMatched = foo2.getElementsByClassName('matched');

            let output2 = '[id가 foo인 태그의 하위 태그 중 class명이 matched인 모든 태그의 text를 출력]\n';
            for(let i = 0; i<fooMatched.length; i++){
                output2 += fooMatched[i].innerHTML + '\n';
            }
            alert(output2);

            //태그 중에서 class명이 matched와 unmatched 모두 적용된 태그를 반환한다
            //클래스 명이 여러 개인 경우 공백을 구분자로해서 문자열로 전달한다.
            //순서는 변경이 가능하다
            const fooMatched2 = foo2.getElementsByClassName('matched unmatched');

            let output3 = '[id가 foo인 태그의 하위 태그 중 class명이 matched unmatched인 태그의 text를 출력]\n';
            for(let i = 0; i<fooMatched2.length; i++){
                output3 += fooMatched2[i].innerHTML + '\n';
            }
            alert(output3);
        };
    </script>
</head>
<body>
    <p id="foo">
        <span class="matched">a</span>
        <span class="matched unmatched">b</span>
        <span class="unmatched">c</span>
    </p>
    <p id="bar">
        <span class="matched">x</span>
    </p>
</body>

Query Selector

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>querySelector</title>
    <script>
        window.onload = function() {
            //명시한 선택자를 통해 해당 선택자를 사용하는 태그를 반환
                                                  //CSS 선택자
            let header1 = document.querySelector('#header_1');
            let header2 = document.querySelector('#header_2');

            header1.innerHTML = '서울';
            header2.innerHTML = '부산';

            let input1 = document.querySelector('#my_form #input_1');
            input1.value = '홍길동';

            //CSS 선택자를 명시하면 여러개의 태그를 반환하는 상황에서도
            //QuerySelector는 같은 태그의 최상단의 태그만 접근 가능하다.
            let element = document.querySelector('li');
            element.style.backgroundColor = 'yellow';
        }
    </script>
</head>

<body>

    <h1 id="header_1">Header</h1>
    <h1 id="header_2">Header</h1>

    <form id="my_form">
        <input type="text" id="input_1">
    </form>

    <ul>
        <li>Apple</li>
        <li>Banana</li>
        <li>Orange</li>
    </ul>

</body>

Query Selector All

    <title>QuerySelectorALL</title>
</head>
<body>
    <ul>
        <li>사과</li>
        <li>바나나</li>
        <li>오렌지</li>
    </ul>
    <script>
        //ul  요소의 자식 요소인 li 요소를 모두 탐색하여 배열로 반환
                                                                // 자식선택자
        const elems = document.querySelectorAll('ul > li');

        for(let i = 0; i<elems.length; i++){
            document.write(elems[i].innerHTML + '<br>');
        }
        document.write('-------------<br>');

        elems.forEach(function(element) {
            element.style.color = 'blue';
        });
    </script>

태그 생성 메소드

메소드설명
createElement(tagName)요소 노드를 생성
createTextNode(text)텍스트 노드를 생성
appendChild(node)객체에 노드를 연결

h1 태그 생성하기

h1 태그에 텍스트를 연결 시켜주고 -> body에 h1을 또 연결시켜주면 h1이 생성된다.

    <script>
        window.onload=function(){
            const header = document.createElement('h1'); //h1 태그 생성
            const textNode = document.createTextNode('Hello DOM'); //text 생성

            //노드 연결
            header.appendChild(textNode); //h1 태그에 텍스트를 추가
            document.body.appendChild(header); //body에 h1 추가
        };

    </script>

img 태그 생성

	<script>
        window.onload = function() {
            const img = document.createElement('img'); //img 태그 생성
            img.src='../files/landscape.jpg';
            img.width=500;
            img.height=350;

            //노드 연결
            document.body.appendChild(img);
        };
    </script>

list 생성

    <script>
        window.onload = function() {
            let output = '';
            output += '<ul>';
                output+= ' <li>JavaScript</li>';
                output+= ' <li>jQuery</li>';
                output+= ' <li>Ajax</li>';
            output += '</ul>';
            
            //innerHTML 속성에 문자열을 할당
            document.body.innerHTML = output;
            // 텍스트로만 처리 시킴
            //document.body.textContent = output;
        }
    </script>

문서 객체 제거하기

    <script>
        window.onload=function() {
            const willRemove = document.getElementById('will_remove');

            //3초 후에 매개변수로 전달된 함수를 호출
            setTimeout(function() {
                //id가 will_remove인 h1 태그 제거
                //document.body.removeChild(willRemove); //하나를 지정하여 삭제

                //문서 객체의 하위 요소를 모두 제거
                document.body.innerHTML=''; // body의 하위 요소들을 모두 지워버리는 것
            },3000);
        };
    </script>
</head>
<body>
    <h1 id="will_remove">Header</h1>
    <h1>Header2</h1>
</body>

Style 입히기

    <script>
        window.onload = function() {
            const header = document.getElementById('header');
			// 문서 객체의 스타일을 바꿈
            header.style.border = '2px solid black';
            header.style.color = 'orange';
            header.style.fontFamily = 'Helvetica';
            header.style.backgroundColor = 'yellow';
        };
    </script>

<body>
    <h1 id="header">Header</h1>
</body>
profile
Lucky Things🍀

0개의 댓글