07-4 자바스크립트 문서 객체 생성, 제거, 이동

onezeun·2022년 2월 2일
0

문서 객체 생성

document.createElement(문서객체이름) : 문서 객체를 생성할 때 쓰는 메소드

객체를 만들었다고 해서 배치까지 되진 않기 때문에 문서를 어떤 문서 아래에 추가할지 지정해 주어야 한다.

어떤 문서 객체가 있을 때 위에 있는것이 부모, 아래있는것을 자식이라고 부른다.

이걸 트리라고 부름

<head>
  <title>createElement 문서 객체 생성</title>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      // 요소 만들기
      // h1 태그 생성
      const header = document.createElement('h1')
      
      // 생성한 태그 조작
      header.textContent = 'createElement로 만든 태그'
      header.style.color = 'red'
      
      const body = document.querySelector('body')
      // 요소 붙이기 (h1태그를 body 태그 아래에 추가하기)
      body.appendChild(header)
    })
  </script>
</head>

appendChild()

생성된 문서 객체를 추가하는 메소드
부모객체.appendChild(자식객체) : 부모 객체 아래에 자식 객체를 추가 할 수있음

문서 객체 제거

<head>
  <title>removeChild 문서 객체 제거</title>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const header = document.createElement('h1')
      header.textContent = 'createElement로 만든 태그'
      header.style.color = 'red'

      const body = document.querySelector('body')
      body.appendChild(header)

      // 2초 뒤에 문서 객체 제거
      setTimeout(() => {
    	header.parentNode.removeChild(header)
        // body.removeChild(header) 이것도 가능
      }, 2000)
    })
  </script>
</head>

실행 결과

removeChild()

부모객체.removeChild(자식객체) : 문서 객체 제거하는 메소드

parentNode

문서객체.parentNode.removeChild(문서객체)
어떠한 요소만 가지고 그 요소 자체를 제거할 수 있기 때문에 이 코드가 더 편해서 많이 사용된다

문서 객체 이동

<head>
  <title>createElement 문서 객체 이동 </title>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      // 문서 객체 읽어들이고 생성하기
      const header = document.createElement('h2')
      header.textContent = '안녕하세요'

      const first = document.querySelector('.first')
      const second = document.querySelector('.second')

      // 서로 번갈아가면서 실행하는 함수 구현
      const toFirst = () => {
        first.appendChild(header)
        setTimeout(toSecond, 1000)
      }
      const toSecond = () => {
        second.appendChild(header)
        setTimeout(toFirst, 1000)
      }
      toFirst()
    })
  </script>
</head>
<body>
  <div class='first'>
    <h1>첫 번째 div 태그 내부</h1>
  </div>
  <hr>
  <div class='second'>
    <h1>두 번째 div 태그 내부</h1>
  </div>
</body>

실행 결과

appendChild()

문서 객체를 이동할 때 사용하는 메소드

profile
엉망진창

0개의 댓글