DOM (Document Object Model)
자바스크립트의 기능이 아닌 브라우저에서 제공하는 기능
HTML 문서 내용을 트리 형태로 구조화 함 -> 웹 페이지와 프로그래밍 언어 연결
문서를 객체화해서 모델링
각각 표현하는 단위를 노드 node
(텍스트, 컨텐츠, 주석 또한 노드로 인식!!)
돔 트리에 접근하기
document 객체로 HTML 문서에 접근 가능
document -> 브라우저가 불러온 웹 페이지를 나타냄
-> DOM 트리의 진입점 역할 수행
document.getElementById()
document.getElementsByTagName();
document.getElementsByClassName();
document.querySelector("selector");
document.querySelectorAll("selector");
console.log(document.getElementsByClassName('item-second')[0]);
console.log(document.getElementsByTagName('li')[0]);
console.log(document.querySelector(".item-second"));
console.log(document.querySelectorAll('li')[3]);
이벤트 삽입
target.addEventListener (type, listener) 형태
target 은 이벤트 삽입할 요소
이벤트 타입에는 click, mouseover, wheel 등 다양한 이벤트를 감지
const myBtn = document.querySelector("button");
myBtn.addEventListener("click", function() {
console.log("hello world");
})
onClick 보다 addEventListener을 추천!!
유지보수성, onClick 은 html과 js가 분리가 안되므로 유지보수 어렵다.
클래스 제어
많이 사용함
const myBtn = document.querySelector("button");
myBtn.addEventListener('click', function() {
myBtn.classList.toggle("blue");
})
.add(); -> 클래스 추가
.remove(); -> 클래스 제거
.toggle(); -> 없으면 넣어주고, 있으면 빼고 눌렀을 때마다 상태가 바뀜
.contains(); -> 해당 클래스가 있는지 없는지 확인 (있고 없음에 따라 다른 스타일), contains는 불리언 값으로 반환
요소 제어
새롭게 생성, 위치, 제거 가능
const myBtn = document.querySelector("button");
const myUl = document.querySelector("ul");
myBtn.addEventListener('click', function(){
for(let i=0; i < 5; i++){
const myLi = document.createElement('li');
const myTxt = document.createTextNode('안녕하세용' + i);
myLi.appendChild(myTxt);
myUl.appendChild(myLi);
}
})
parentElement.insertBefore(target, location); target요소를 parentElement의 자식인 location 위치 앞으로 이동합니다.
문자열을 이용한 element, text 노드를 생성하거나 추가
myP.textContent = myInput.value;
innerText vs textContent
innerText -> 줄바꿈, 사람이 읽을 수 있는 요소만 처리
-> 뭄법들도 다 담아내서 결과물을 가공하여 반환
textContent -> 텍스트 자체로 인식해서 던짐
-> 인식 못하는거 제외하고 전달
innerText 사용시 주의사항
웹 페이지에 텍스트 삽입 -> 보안 취약
크로스사이트 스크립트 공격 같지만, HTML5은 innerText와 함께 전달된 스크립트 태그를
실행하지 않도록 지정함
일반 텍스트 삽입 할 때는 innerHTML 대신 textContent 사용을 권장
더 인접한곳 (Adjacent)으로 정밀하게 배치
요소 노드를 주어진 위치에 배치
.insertAdjacentHTML('beforebegin', '<span>안녕하세요 저는</span>');
beforebegin -> 요소 앞에
afterbegin -> 요소 안 가장 첫번째 자식
beforeend -> 요소 안 가장 마지막 자식
afterend -> 요소 뒤에
돔 안에서 노드 탐색
.firstElementChild -> 첫 번째 자식
.lastElementChild -> 마지막 자식
.nextElementSibling -> 다음 형제 요소
.previousSibling -> 이전 형제 노드
.previousElementSibling -> #text가 아닌 요소를 찾고 싶다면
.children -> 모든 직계 자식
.childNodes -> NodeList 출력
.parentElement -> 부모 요소 찾음
이벤트 객체
이벤트에서 호출되는 핸들러
event 관련된 정보 출력
btnFirst.addEventListener('click', (event) => {
console.log(event);
});