문서 객체 모델과 이벤트 기본

peter.p·2022년 1월 12일
0

Javascript

목록 보기
21/23
  • 문서 객체 모델
    Document Object Model(DOM).
    문서 객체는 HTML요소, 문서 객체 모델은 그걸 조작하는 객체들의 집합이다.
    - document.body.innerHTML += '<h1></h1>'
    문서 객체 내의 바디 객체 내에 있는 innerHTML에 h1태크 만들어주기.
    *innerHTML: 문자열 → += '' += 을 통해서 문자열을 추가할 수 있다.

    결과값.
    왜 이렇게 나올까?? A를 추가하는 시점에서는 body태그가 아직 생성되기 전이다. 그래서 B, 안녕하세요!, C 만 출력.
  • DomContentLoaded
    위에서 A도 출력되게 하고 싶으면 document.addEventListener('DOMContentLoaded', ()=>{}) 를 사용. DOMContentLoaded라는 이벤트가 발생하면 ()=>{} 콜백함수 호출
  • 문서 객체 가져오기
  • document.querySelector()
    선택자를 읽어들이는 메서드.
    • 선택자의 종류
      • 태그 선택자
        document.querySelector('h1')
        HTML = <h1 id="header" class = "header2 center"></h1>
        -활용:
        const h1 = document.querySelector('h1')
        h1.style.color = 'red'
      • 아이디 선택자
        document.querySelector(#header)
        HTML = <h1 id="header" class = "header2 center"></h1>
        -활용:
        document.querySelector(#header).style.backgroundColor = 'red'
      • 클래스 선택자
        HTML = <h1 id="header" class = "header2 center"></h1>
        -활용:
        document.querySelector(.header2)
        document.querySelector(.header2.center) //클래스 선택자가 2개일때
        document.querySelector(h1#header.header2.center)
      • 속성 선택자
        document.querySelector(.header2)
        HTML = <input type ="text">
        -활용:
        document.querySelector('[type = text]').style.borderRadius = 10px
      • 후손 선택자
        document.querySelector('body input')
        body 태그 안에 있는 모든 input에 적용.
  • document.querySelectorAll()
    <script>
        document.addEventListener('DOMContentLoaded', ()=>{
            for(const element of document.querySelectorAll('input')){
                element.style.backgroundColor = 'red'
            }
        })
    </script>
  • 글자 조작하기.
    textContent는 문자그대로 받지만,
    innerHTML는 html을 반영한다.


  • 속성 조작하기
  • 스타일 조작하기


    ※ 중간정리
  • 문서 객체 생성하기.
  • 문서 객체 이동하기.
  • 타이머 관련 테크닉(1)
    위 아래로 '안녕!' 이 왔다갔다 하게 됌.
  • 타이머 관련 테크닉(2)
    위에 것과의 차이. 시작할 때는 안녕!이 없다가 1초 후에 안녕!이 나타남.
    똑같이 만들어 주려면 interval 밑에 fun()으로 강제 호출.
  • 이벤트 연결하기
profile
꼭 웹 퍼플리셔가 될거에요

0개의 댓글

관련 채용 정보