1. 노드 접근
DOM 은 Document Object Model 의 약자입니다.
html 문서의 각 요소들을 tree 형식으로 표현해주는 데 이를 DOM TREE 라고 합니다.
트리구조에서 하나의 개체를 노드(Node)라고 부릅니다.
트리에서 위쪽은 부모노드, 아래쪽은 자식노드라고 합니다.
도큐먼트를 제외한 최상단의 html 은 root node 가 됩니다.
모든 html 태그는 document 객체로 접근하고 제어할 수 있습니다.
1document.documentElement // html 에 접근2document.body // body 태그에 접근3document.head // head 태그에 접근
document.body.style: 스타일이 담긴 객체 확인document.body.style.backgroundColor = "red": 배경 색 변경document.body.style.opacity = "0";: 투명도 조절document.body.style.padding = "100px";: 패딩 조절
1.1 get 메서드 : 속성값과 태그명
getElementById( id 속성값 ): id 접근getElementsByClassName( class 속성값 ): 클래스 이름 접근getElemenetsByTagName( 태그명 ): 태그 이름 접근
1<!doctype html>2<html lang="ko">3<head>4<meta charset="UTF-8" />5<title>요소 노드 선택하기</title>6</head>7<body>8<h1 id="title">title</h1>9<p class="text">text-1</p>10<p class="text">text-2</p>11<script>12// id 속성값이 title인 요소 노드 선택13const el = document.getElementById('title')14console.log(el) // <h1 id="title">1516// class 속성값이 text인 요소 노드 모두 선택17const classEl = document.getElementsByClassName('text')18console.log(classEl) // HTMLCollection { 0: p.text, 1: p.text, length: 2 }19console.log(classEl[0]) // <p class="text">text-1</p>20console.log(classEl[1]) // <p class="text">text-2</p>2122// p 태그에 해당하는 요소 노드 모두 선택23const tagEls = document.getElementsByTagName('p')24console.log(tagEls) // HTMLCollection { 0: p.text, 1: p.text, length: 2 }25console.log(tagEls[0]) // <p class="text">text-1</p>26console.log(tagEls[1]) // <p class="text">text-2</p>27</script>28</body>29</html>
getElementById()로 선택하는 요소 노드- 무조건 1개이기 때문에 해당 요소 하나만을 보여줌
getElementsByClassName(), getElementsByTagName()로 선택하는 요소 노드- HTMLCollection 객체로 여러 요소를 한꺼번에 선택
1.2 query 메서드 : CSS 선택자⭐
document 객체의 get 메서드와 query 메서드는 둘 다 원하는 요소 노드를 선택한다는 점은 같습니다. 하지만 query 메서드는 매개변수로 CSS 선택자를 전달받기 때문에 get 메서드보다 범용성이 더 좋습니다. 그래서 대부분 query 메서드를 주로 사용합니다.
querySelector( CSS 선택자 )- 매개변수로 넘어오는 CSS 선택자에 해당하는 노드를 1개만 선택
querySelectorAll( CSS 선택자 )- 매개변수로 넘어오는 CSS 선택자에 해당하는 노드를 모두 선택
💡 이론적으로만 따지자면,
- 성능은 특정 매개변수만 전달받는 get 메서드가 query 메서드보다 좋습니다.
- 현대 웹에서는 신경쓰지 않아도 될 정도의 차이라서 query 메서드를 사용하는 것이 더 나음
1<!doctype html>2<html lang="ko">3<head>4<meta charset="UTF-8" />5<meta http-equiv="X-UA-Compatible" content="IE=edge" />6<meta name="viewport" content="width=device-width, initial-scale=1.0" />7<title>querySelector-*</title>8</head>9<body>10<div class="box-1">11<p class="text">text-1</p>12<p class="text">text-2</p>13</div>14<div class="box-2">15<p class="text">text-3</p>16<p class="text">text-4</p>17</div>18<script>19// 📝 class 속성값이 box-1인 요소 노드를 선택20const el1 = document.querySelector('.box-1')21console.log(el1) // <div class="box-1">2223// get 메서드로 class 속성값이 box-1인 요소의 하위에 있는 p 태그24const el2 = document.getElementsByClassName('box-1')[0].children25console.log(el2) // HTMLCollection { 0: p.text, 1: p.text, length: 2 }2627// query 메서드로 class 속성값이 box-1인 요소의 하위에 있는 p 태그28const el3 = document.querySelectorAll('.box-1 .text')29console.log(el3) // NodeList [ p.text, p.text ]30</script>31</body>32</html>
1.3 응용 : 여러 개 선택
여러개의 p 값을 선택하면 해당 값을 배열 모양을 반화하는데 배열은 아닙니다. 배열처럼 생긴 리터럴한 컬렉션이라서 배열처럼 호출하거나 갯수를 확인할 수 있습니다.
pList[1]- 이렇게 호출할 수 있고pList.length- 갯수도 알 수 있긴 함
array 메소드는 사용할 수 없어서 아래처럼 for of 로 순회하며 값을 적용할 수 있습니다.
1for (p of pList) {2p.style.fontsize = '30px'3}45for (p of pList) {6p.style.opacity = String(Math.random())7}
아래와 같은 선택 방법도 많이 사용합니다.
1document.querySelectorAll('.link') // class 명으로 선택 가능2document.querySelector('#first') // id 는 앞에 #을 붙여서34document.querySelector('h3:nth-of-type(2)')5// 이렇게 하면 두번째 h3 태그만 선택67document.querySelector('h3:nth-of-type(2)').style.color = 'red'8// 이렇게 색 변경 가능910document.querySelector('p:nth-of-type(2n)')11// 2n 이라고 하면 짝수번째 것들만 선택
2. 부모, 자식, 형제 노드 접근
document 객체는 트리를 탐색하면서 원하는 노드를 선택할 수 있는 속성을 제공합니다.
| 모든 모드 | 요소 노드만 | |
|---|---|---|
| 부모 | parentNode | parentElement |
| 자식 | childNodesfirstChildlastChild | childrenfirstElementChildlastElementChild |
| 형제 | previousSiblingnextSibling | previousElementSiblingnextElementSibling |
2.1 부모노드 접근
1const red = document.getElementById('red')2// id 가 red 인 태그 선택하고34red.parentNode5// 부모노드 선택67red.parentElement8// 이렇게 요소만 접근도 가능910document.documentElement.parentNode11// document 반환1213document.documentElement.parentElement14// nuul 반환. 부모 노드에게 엘리먼트가 없으므로
2.2 자식노드 접근
1const ul = document.getElementById('color')23ul.childNodes // 자식 노드 (안의 요소, 텍스트 등등 따로) 반환4ul.children // html 요소만 반환 li 태그들의 데이터 집합으로.56ul.firstChild // 첫번째 노드의 모든 타입7ul.lastChild // 마지막 노드의 모든 타입89ul.firstElementChild // 첫번재 요소만10ul.lastElementChild // 마지막 요소만
2.3 형제노드 접근
형재 노드는 이전과 이후로 선택할 수 있습니다.
1// 이전과 이후 요소의 모든 타입2blue.previousSibling3blue.nextSibling45// 해당 요소만 반환6blue.prebiousElementSibling7blue.nextElementSibling