[프론트엔드] JavaScript 문서객체모델(DOM)

박민우·2022년 10월 24일
0

프론트엔드

목록 보기
6/6

DOM이란?

* Document Object Model

* HTML 문서에접근하기위한인터페이스(interface)

기본 DOM

* 페이지 로드 : DOMContentLoaded

* 요소 선택 : querySelector, getElementByClassName 등

querySelector

<body>
  <h1 class="txt">안녕하세요</h1> 
  <script>
    //문서에 class가 txt인 요소를 header에 저장
    const header = document.querySelector('.txt')
    console.log(header)
  </script>
</body>

출력화면 ==>

querySelectorAll

<body>
    <h1 class="txt">헬로</h1>
    <h1 class="txt">니하오</h1> 
    <h1 class="txt">봉주르</h1> 
    <h1 class="txt">안녕</h1> 
        <script>
          //문서에 class가 txt인 모든 요소를 headers에 저장
          const headers = document.querySelectorAll('.txt')
          console.log(headers)
        </script>
</body>

출력화면 ==>

* 글자 조작 : textContent, innerHTML

<body>
    <div id="a"></div>
    <div id="b"></div>
    <script>
        const a = document.querySelector('#a')
        const b = document.querySelector('#b')

        //텍스트 형태로 태그 사이에 넣어준다
        a.textContent = '<h1>textContent 속성</h1>' 
        //태그 형태로 태그 사이에 넣어준다.
        b.innerHTML= '<h1>innerHtml 속성</h1>'
    </script>
</body>

출력 화면 ==>

querySelector로 지정한 ₩div 태그 안으로 값이 들어간다

* 속성 조작 : setAttribute, getAttribute

setAttribute

<body>
    <div class="rect"></div>
        <script>
          const rect1 = document.querySelector('.rect')
          
          rect1.setAttribute('style', 'border : 1px solid black; width : 100px; height : 100px')

        </script>
</body>

출력 화면 ==>

지정한 태그 안에 넣을 속성을 요소.setAttribute('속성명','속성 값') 형식으로 작성

* 태그 조작 : createElement, appendChild, removeChild

<body>
    <div class="box">
        첫번째 div
        <span class="inner">테스트 입니다.</span>
    </div>
    <script>
        //요소 생성
        const header = document.createElement('h1')
        console.log(header)		//header => <h1></h1>
        //문서 안에 body 안에 자식요소로 header(h1태그)를 넣어줌
        document.body.appendChild(header)
        
        //querySelector로 가져온 요소에 적용 가능
        const box = document.querySelector('.box')
        const spanTag = document.querySelector('span')
        box.appendChild(header)

        //box 안에 span 요소 제거
        box.removeChild(spanTag)
    </script>
</body>

==> 출력화면

div.box 안에 h1태그가 생성되었다.

  • createElement : 문서에 넣을 태그 생성
  • appendChild: 문서에 자식요소로 지정한 태그를 넣어줌
  • removeChild: appendChild와 반대로 지정한 요소 제거

* 이벤트 : addEventListener, removeEventListener

<body>
    <h1>클릭횟수 : 0</h1>
    <script>
        let counter = 0
        const h1 = document.querySelector('h1')
        //addEventListener('이벤트 명', '함수')
        
        h1.addEventListener('click', function(){
            //클릭 시 실행되길 원하는 코드
            counter++
            h1.textContent =  `클릭횟수 : ${counter} `
        })
        //removeEventListener('지우고싶은 함수명',콜백 함수)
        h1.removeEventListener('click',listener)
    </script>
</body>

==> 출력화면

클릭 횟수를 클릭하면 횟수를 1씩 증가시키는 함수

  • addEventListener : querySelector로 가져온 요소에 이벤트 설정
  • removeEventListener : 설정한 이벤트를 삭제시키는 설정
profile
멋쟁이 백엔드 개발자가 되어보자

0개의 댓글