HTML DOM은 브라우저가 HTML을 파싱해 노드(부모–자식) 트리로 만든 모델이며, 자바스크립트로 (element)요소를 선택/읽기/변경/추가/삭제할 수 있게 해주는 표준이다.
https://www.w3schools.com/js/js_htmldom.asp
window.document)<div>, <p>). 대부분 우리가 조작하는 대상.// 1) ID로 1개 선택 (가장 빠르고 많이 씀)
const ex = document.getElementById('example');
// 2) 태그/클래스으로 "라이브 컬렉션" 얻기
const pList = document.getElementsByTagName('p'); // HTMLCollection
const items = document.getElementsByClassName('item'); // HTMLCollection
// 3) CSS 선택자
const one = document.querySelector('.card'); // 첫 번째 요소 1개
const many = document.querySelectorAll('.card'); // 모든 card class ,NodeList(정적)
const secondH3 = document.querySelector('h3:nth-of-type(2)'); // 2번째 h3
getElementsByTagName, getElementsByClassName 등에서 반환querySelectorAll의 NodeList는 정적(DOM 변경 자동 미반영)
childNodes가 반환하는 NodeList는 텍스트/주석/요소 모두 담고 라이브이다.
const html = document.documentElement;
// 부모
html.parentNode; // #document (문서 노드)
html.parentElement; // null (문서의 부모는 태그 요소가 아님 부모가 요소일대만 반환한다.)
// 자식
html.childNodes; // (NodeList) 텍스트/주석/요소 모두 포함
html.children; // (HTMLCollection) "요소"만
// 형제/자식 편의 접근
element.firstElementChild;
element.lastElementChild;
element.previousElementSibling;
element.nextElementSibling;
// <li>green</li> 만들기
const newLi = document.createElement('li');
newLi.textContent = 'green';
const ul = document.getElementById('color');
ul.appendChild(newLi); // 마지막 자식으로 추가
ul.innerHTML += '<li><strong>pink</strong></li>';
textContent vs innerHTMLtextContent: 문자 그대로 넣음(HTML 해석 X) → 빠르고 안전(XSS 위험 적음)innerHTML: 문자열을 HTML로 파싱한다. 즉 태그를 포함한다. 파싱하기에 속도가 느림→ 편하지만 성능/보안 주의 사용자 입력을 그대로 innerHTML에 넣으면 태그를 입력받을수 있기에 보안상 위험하다// <li>green</li> --> <li>yellow</li>
const another = document.createElement('li');
another.textContent = 'yellow';
newLi.replaceWith(another); // 교체
newLi.remove(); // 자기자신 제거
const box = document.getElementById('box');
box.style.backgroundColor = 'red';
box.style.width = '100px';
box.style['margin-left'] = '30px';
위와 같이 box 라는 id 태그를 가진 요소에 접근하여 style을 바꿔줄수있다.
event는 마우스를 클릭하거나, 키보드를 누르는것 과 같이 일어나는 이벤트를 의미한다.
event가 발생할 때 특정함수를 호출해서 쓸 수있는데 이를 eventHandler 라고한다.
<button onclick="alert('click1')">클릭1 </button>
<button onclick="sayHello(2)">클릭2 </button>
<input id="txt1" type="text" />
<input id="txt2" type="text" />
function sayHello(num){
alert('click' + num);
}
const input = document.getElementById('txt1');
input.addEventListener('click', () => sayHello(3));
const input2 = document.getElementById('txt2');
input2.addEventListener('keydown', (event) => {
// text 창에 enter 키가 눌리면 enter! 경고창 출력된다.
if (event.key === 'Enter') alert('enter!');
});