제수기 > Javascript > Access DOM

Eunbi Jo·2025년 1월 3일
0

제수기

목록 보기
41/90
제수기 - 제발 수업내용을 기억해라

Access DOM

DOM Document Object Model (객체지향언어)

  • HTML 문서의 모든 요소를 객체로 변화해서 관리
  • html 문서가 브라우저에 로드될 때, 브라우저 내부 js엔진의 html계층구조를 그대로 본따 DOM을 생성
  • document라는 객체를 통해 dom에 접근

html 파일

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS | Access DOM</title>
</head>
<body>
    <h1>Access DOM</h1>
    <!-- DOM Document Object Model
    - 객체지향언어
    - HTML 문서의 모든 요소를 객체로 변화해서 관리
    - html 문서가 브라우저에 로드될 때, 브라우저 내부 js엔진의 html계층구조를 그대로 본따 DOM을 생성
    - document라는 객체를 통해 dom에 접근
    -->
    <!-- ul>(li>button[type=button])*5 -->
    <ul style="list-style-type:none; padding-left:0;"">
        <button type="button" onclick="test1()">id</button>
        <button type="button" onclick="test2()">tag</button>
        <button type="button" onclick="test3()">class</button>
        <button type="button" onclick="test4()">css - quertSelector</button>
        <button type="button" onclick="test5()">css - querySelectorAll</button>
    </ul>

    <!-- ul>li#li$.group1{Hello JS$}*5 -->
    <ul>
        <li id="li1" class="group1">Hello JS1</li>
        <li id="li2" class="group2">Hello JS2</li>
        <li id="li3" class="group1">Hello JS3</li>
        <li id="li4" class="group2">Hello JS4</li>
        <li id="li5" class="group1 group2">Hello JS5</li>
    </ul>

    <button type="button" onclick="test6()">name</button>

    <form action="">
        <fieldset>
            <legend>취미 선택</legend>
            <div>
                <label for="checkAll">모두 선택</label>
                <!-- tag 객체 이벤트 속성에서 사용된 this는 tag 객체 자신을 가리킨다. -->
                <input type="checkbox" id="checkAll" oncahnge="checkAllHobbies(this)">
            </div>

            <!-- div>(label[for=hobby$]+input:checkbox[name=hobby]#hobby$)*3 -->
            <div>
                <label for="hobby1">넷플릭스</label><input type="checkbox" name="hobby" id="hobby1" value="netflix">
                <label for="hobby2">클라이밍</label><input type="checkbox" name="hobby" id="hobby2" value="climing">
                <label for="hobby3">러닝</label><input type="checkbox" name="hobby" id="hobby3" value="running">
            </div>
        </fieldset>

        <fieldset>
            <legend>@실습문제 : input태그 사용자입력값 출력하기</legend>
            <label for="name">이름</label>
            <input type="text" name="name" id="name" class="user-input" value="홍길동" >
            <button type="button" onclick="test7();">확인</button>
        </fieldset>
        <fieldset>
            <legned>점수</legned>
            <label for="score">점수입력 : </label>
            <input type="range"
            name="score"
            id="score"
            min="0"
            max="100"
            value="100"
            oninput="test8(this)">
            <!-- oninput : input태그의 값이 바뀔 때마다 적용 -->
            <span id="display-score"></span></fieldset>
    </form>

    <script src="js/04_access_dom.js"></script>
</body>
</html>

document.getElementById(id): Element

존재하면 해당 tag 객체를 반환하고

    • 존재하지 않으면 null을 반환한다.

document.getElementsByTagName(tagName): HTMLCollection

매칭되는 tag객체를 배열형태로 반환

document.getElementsByClassName(className) : HTMLCollection

document.querySelector(cssSelector):Eelement

css선택자에 매칭된 태그 객체 중 첫번째 객체 반환

    • 매칭된 객체가 없으면 null 반환

document.querySelectorAll(cssSelector):NodeList

매칭되는 요소를 배열 형태로 반환

    • 매칭되는 요소가 없으면 빈 배열 반환

document.getElementsByName(name):NodeList

checkAll을 클릭하면 모든 취미를 체크/체크해제

실습문제


/**
 * @실습문제 : input 태그 사용자입력값 출력하기
 */

function test7(){
    // id로 가져오기
    // const $name = document.getElementById('name');
    // console.log($name, typeof($name));
    // class로 가져오기
    
    // name으로 가져오기
    // const $name = document.getElemnetByName('name');
    // const $name = document.querySelector('#name')
    // const $name = document.querySelector('.user-input')
    const $name = document.getElementsByName('name')[0]
    console.log($name);

    const nameVal = $name.value;
    console.log(nameVal);
}

/**
 * input: range value 시각화
 */
function test8($score){
    const scoreVal = $score.value
    // console.log(scoreVal);

    // 0 태그를 가져와서 계속 바뀌는 value값을 반영
    const $displayScore = document.querySelector('#display-score');
    $displayScore.innerHTML = scoreVal;
}

/**
 * HTML -> DOM 객체 로드가 완료되면 실행하기
 */
document.addEventListener('DOMContentLoaded', function(){
    console.log('DOMContentLoaded');

    // 위와 같은 이벤트가 발생하면, 아래와 같이 해주세요~ 라고 요청한 것.
    // #score 초기값 시각화
    const $score = document.getElementById('score');
    test8($score);
});

0개의 댓글