본문 바로가기
개발공부_Blog/JavaScript

javascript - createElement / appendChild / removeChild

by 독서개발자 2021. 12. 19.

 문서 객체를 생성 할 때 

# 문서 객체 생성하기
documena.createElement( 문서객체이름 )

# 문서 객체 추가 ( 부모객체 아래에 자식객체 추가 )
document.appendChild( 자식 객체 )

 

  예제  코드 (1)  

document.addEventListener('DOMContentLoaded',()=>{
  const header = document.createElement('h1') // h1 태그를 생성한다

  header.textContent = '문서객체 동적으로 생성하기'	// text를 추가한다
  header.style.color = 'white' // style속성을 추가한다
  header.style.backgroundColor = 'tomato'

  document.body.appendChild(header)	// h1 태그를 body태그 아래에 추가
})

 

 

 

  예제  코드 (2)  

<script>
document.addEventListener('DOMContentLoaded',()=>{
  const divA = document.querySelector('#first')
  const divB = document.querySelector('#second')
  const h1 = document.createElement('h1')  // h1태그를 만든다
  h1.textContent = '이동하는 h1태그'       // h1 안에 text를 추가한다

  const toFirst = () => {              // toFirst함수 
    divA.appendChild(h1)               // divA에 h1을 추가한다
    h1.style.backgroundColor='tomato'  // h1 배경색 tomato
    setTimeout(toSecond, 1000)         // settimeout : 일정시간 뒤에 함수실행
  }        // ( 실행할 함수 , 시간 )
  
  const toSecond = () => {
    divB.appendChild(h1)
    h1.style.backgroundColor='skyblue'
    setTimeout(toFirst, 5000)
  }
  toFirst()
})
</script>

<body>
  <div id="first">
    <h1>첫 번째 div 태그 내부</h1>
  </div>
  <div id="second">
    <h1>두 번째 div 태그 내부</h1>
  </div>
</body>

 

toFirst() 함수를 실행한다. 

1초 후에 toSecond() 함수를 실행하고, 5초 뒤에 toFirst() 함수를 실행한다 

 

 

 

 

 

  문서객체 제거  

부모객체.removeChild(자식객체)
문서객체.parentNode.removeChild(문서객체)

 

  예제  코드   

<script>
document.addEventListener('DOMContentLoaded',()=>{
  const header = document.createElement('h1')   // h1태그 지정
 
  setTimeout(() => {                        // setTimeout(): 일정시간 후 함수실행
    const h1 = document.querySelector('h1') // h1태그 생성
    h1.parentNode.removeChild(h1)           // h1태그의 부모 객체 body에 접근해 제거

  }, 3000);

})
</script>

<body>
<hr></hr>
<h1>제거 대상 문서 객체</h1>
<hr></hr>
</body>

 

h1 태그의 부모객체 = document.body와 같으므로 아래와 같은 코드도 가능

h1. parentNode.removeChild(h1) = h1.document.body.removeChild(h1))

3초가 지나면 '제거 대상 문서 객체'인 h1태그는 지워진다

 

 

 

댓글