1. append & appendChild
- 두 메서드는 모두 부모 자식에 자식 노드를 추가하는 메서드이다.
자식 노드를 추가하는 방식이 서로 다르다.
append
- 노드 객체와 DOM string(Text) 관리 가능
- 한번에 여러개의 자식 요소 설정 가능
- return 값을 반환하지 않는다.
const boxParent = document.createElement('div')
const boxChild = document.createElement('p')
const lastChild = document.createElement('span')
lastChild.append('이것은 요소')
boxChild.append(lastChild, 'hello') //text추가
boxParent.setAttribute('class', 'parent')
boxParent.append(boxChild)
document.body.append(boxParent)
appendChild
- 오로지 node 객체만 자식 요소로 추가할 수 있다.
- 한개의 node 객체만 추가할 수 있다.
- append는 text를 바로 추가할 수 있었지만 appendChild는 따로 createTextNode를 만든 후 해당 요소를 appendChild해주었다.
let createEleme = document.createElement('div')
let textNode = document.createTextNode('생성완료')
createEleme.setAttribute('class', 'newDiv')
createEleme.appendChild(textNode)
document.body.append(createEleme)
2. 생성
createElement() & createTextNode()
참고사이트