STUDYING/Javascript
[JS] DOM & EVENT #1 노드에 접근하기
sustronaut
2022. 5. 17. 10:52
1. DOM (Document Object Model)
DOM은 html의 각 요소들을 트리 형식으로 표현해주는 자료구조이며 개발자는 JS로 이것들을 수정하거나 삭제하거나 생성 가능

- 하나의 객체를 노드라고 함
- 부모 노드와 자식 노드로 구분
2. 모든 html 태그는 객체로 구성
- - 콘솔창에 : document.documentElement 하면 html 태그 안의 코드가 출력 document.body; 하면 body 태그 안의 있는 코드가 출력
- 태그명으로 접근 : document.getElementsByTagName('p')' -> p태그로 접근
- className로 접근하기
- className으로 접근 : 1) document.getElementsByClassName('link') -> className이 link인 곳으로 접근
- querySelectorAll으로 접근 : 2) documet.querySelectorAll('.link'); -> className이 link인 모든 곳으로 접근
- id로 접근하기
- id로 접근 : document.getElementId('first');
- querySelector으로 접근 : document.querySelector('#first'); -> 가장 첫번째로 오는 #first가 출력
- querySelectorAll로 하면 #first인 모든 것들을 가져오게 됨
- 원하는 태그 가져오기
- document.querySelector('h3:nth-of-type(2)').style.color="blue" -> h3태그 중 2번째로 오는 것 가져와 색깔을 파랑으로 바꿈
- const pList = document.querySelector('h3:nth-of-type(2n)') -> 짝수번째 h3태그만 선택 -> pList는 배열x, nodeList임(iterable한 컬렉션)
- for (p of pList) { p.style.backgroundColor='#000'} -> 짝수번째 h3태그만 배경색을 검정으로 설정
3. nodeList
- 배열x, iterable한 컬렉션
- pList[1] 처럼 각 노드에 인덱션으로 접근 가능
- pList.length 가능
- 하지만 배열은 아님
- push(), pop(), filter(), join() 불가능
출처 : 유튜브 - 코딩앙마