자주 사용하고 기억해야하는 메서드들 입니다..
계속계속 수정하고 추가할 예정이에요!
요소 선택 | |
.querySelectorAll('li') | li 요소를 모두 선택 - NodeList() 반환 - 요소 추가 등 업데이트시 반영되지않음. - 보다 다양한 쿼리를 지원 |
.getElementsByTagName('li') | li 요소를 모두 선택 - HTMLCollection() 반환 - 요소 추가 시 자동 업데이트됨. |
삽입 , 제거 , 교체 | ||
old 메서드 | new 메서드 (브라우저 지원 안될 수 있음) |
|
appendChild() | append() prepend() |
DOM 객체 삽입 (첫번째 또는 마지막 삽입) |
insertAdjacentElement() | before() after() |
DOM 객체 삽입 (특정 요소 뒤 또는 앞 삽입) |
replaceChild() | replaceWith() | DOM 요소 교체 |
removeChild() | remove() | DOM 요소 제거 |
예시
const list = document.querySelector('ul') | 스크립트의 HTML 요소인 ul 을 선택 |
const newLi = document.createElement('li') | li 요소를 새롭게 만들어 변수에 담음 |
newLi.textContent = 'Item4' | li 에 text를 추가 |
list.prepend(newLi) | ul의 자식요소 가장 첫번째에 li 삽입 |
list.lastElementChild.before(newLi) | ul의 마지막 요소 앞으로 li 이동 ( list.prepend(newLi)로 DOM에 추가가 된 상태이기 때문에 새롭게 삽입, 복사가 아닌 이동.) |
list.firstElementChild.replaceWith('d') list.firstElementChild.replaceWith(newLi) |
ul의 가장 첫 요소가 text 'd' 로 교됨. newLi이 ul의 가장 첫 요소로 이동함. 두 경우 모두 가장 첫요소는 삭제된다. |
const secondLi = list.children[1] | list 의 2번째 자식을 선택 |
secondLi.insertAdjacentElement('afterend',newLi) | secondLi 요소 뒤에 newLi 요소를 삽입함. |
const newLi2 = newLi.cloneNode(true) | newLi 요소를 복사 (true: 자신, 자식, 자손까지 복제됨 / false : 자신만 복제) |
list.append(newLi,newLi2) | list에 newLi 와 newLi2를 추가함. 이때 , 가장 마지막에 추가 이미 삽입되어 있던 요소는 마지막으로 자리를 이동함. |
list.remove | DOM에서 요소 삭제 |
list.parentElement.removeChild(list) | list의 부모로 이동 후 list 요소 삭제 |