DOM을 JavaScript로 조작하여 HTML Element를 추가하거나 삭제, 혹은 내용을 변경할 수 있다.
- createElement - CREATE
- querySelector, querySelectorAll - READ
- textContent, id, classList, setAttribute - UPDATE
- remove, removeChild, innerHTML = "" , textContent = "" - DELETE
- appendChild - APPEND
- innerHTML과 textContent의 차이
DOM?
DOM(Document Object Model): 브라우저 환경에서 html 문서의 요소에 접근하거나 생성, 삭제 하기 위한 일종의 인터페이스로서 모델 내의 각 객체에 접근하고 수정할 수 있는 프로퍼티와 메소드를 제공한다.
DOM이라는 구조를 기반으로, js로 html을 조작하고, document 객체를 통해 html에 접근한다(BOM: window 객체를 통해 브라우저 접근)
html 구조가 js의 객체 구조와 같은 tree구조라서, js의 DOM이 브라우저에 접근하기 가장 바람직하다
CREATE - createElement
// createDiv 변수에 생성된 div element 할당
// 생성만 된 상태
const createDiv = document.createElement('div')
// createDiv를 트리 구조와 연결
document.body.append(createDiv)
// querySelector로 클래스 이름이 user인 html 요소를 조회
const userName = document.querySelector('.user')
// 여러개의 요소를 한 번에 가져오기 위해, querySelectorAll
// html 요소를 배열처럼 for문 사용 가능하지만 유사 배열(Array-like Object)
const users = document.querySelectorAll('.user')
// 비어있는 div 요소에 문자열 입력
console.log(createDiv) // <div></div>
createDiv.textContent = 'hokiki'
console.log(createDiv) // <div>hokiki</div>
// css 적용하기 위한 div 요소에 class 추가
createDiv.classList.add('.style')
console.log(createDiv) // <div class="style">hokiki</div>
// append를 이용해 container의 자식 요소로 추가
const container = document.querySelector('#container')
container.append(createDiv)
setAttribute(attribute, value)
class와 id 말고 attribute를 추가하고 설정하는 메소드
getAttribute(attribute)
attribute의 값을 취득
removeAttribute(attribute)
지정한 attribute를 제거
DELETE - remove, removeChild
createDiv.remove() // create, update한 변수 createDiv를 삭제
document.querySelector('#container').innerHTML = ''; // container 하위 요소 모두 제거
// 이 방식은 보안상의 이유(XSS Attack)로 권장하지 않는다
// container의 첫 번째 요소가 존재하면, 첫 번째 자식 요소를 제거
const container = document.querySelector('#container');
while (container.firstChild) {
container.removeChild(container.firstChild)
}
// container의 자식 요소가 1개만 남을 때까지, 마지막 자식 요소를 제거
const container = document.querySelector('#container');
while (container.children.length > 1) {
container.removeChild(container.lastChild)
}
// 직접 클래스 이름을 특정한 요소만 찾아서 지우는 방법
const snoopys = document.querySelectorAll('.snoopy')
snoopys.forEach(function(snoopy) {
snoopy.remove()
})
// or
for (let snoopy of snoopys) {
snoopy.remove()
}
기초적인 event를 알고, event handler를 element에 적용할 수 있다
- onclick event
- onclick 에 직접 할당하는 것과 addEventListener의 차이
- eventHandler 함수를 만들고, eventHandler의 첫번째 인자를 사용할 줄 안다.
function (e) // e -> error
const button = document.querySelector('.button);
button.onclick = funtion () {
alert('clicked');
}
const button = document.querySelector('.button');
button.addEventListener('click', function (e) {
// 이벤트 핸들러는 메소드이므로 내부의 this는 이벤트에 바인딩된 요소를 가리킴
console.log(this); // <button id="button">Button</button>
console.log(e.currentTarget); // <button id="button">Button</button>
console.log(e.currentTarget === this); // true
});
<body>
<button>아메리카노</button>
<button>카페라떼</button>
<script>
let menus = document.querySelectorAll("button"); //모든 버튼을 가져옵니다.
let btnAmericano = menus[0];
let btnCaffelatte = menus[1];
function handleClick(event) {
// event.target.value는 클릭한 tag에 value 속성이 있을 때만 !== undefined
let currentMenu = event.target.textContent;
console.log(currentMenu + "를 클릭하셨습니다.");
}
btnAmericano.onclick = handleClick; // 아메리카노를 클릭하셨습니다
btnCaffelatte.onclick = handleClick; // 카페라떼를 클릭하셨습니다
</script>
</body>
console.dir: 엘리먼트의 부모와 자식을 탐색할 수 있음 ex) console.log(document.body)
문제를 함수로 쪼개는 것이 좋은 이유: 재사용성, 일관된 코드 작성
html 구조를 DOM을 이용해서 만들기👇🏻
<div class="man">
<div class="name">snoopy</div>
</div>
let dom = document.createElement('div')
dom.classList.add('man')
let domdom = document.createElement('div')
domdom.classList.add('name')
domdom.textContent = 'snoopy'
dom.appendChild(domdom)
document.body.appendChild(dom)
document.body.appendChild(domdom)