JavaScript 20장 - 개념짚기 (14)
포스트
취소

JavaScript 20장 - 개념짚기 (14)

JavaScript

DOM (Document Object Model)

  • 문서 객체 모델로, HTML 문서의 각 요소들을 트리 형태로 표현해준다.
  • 모든 HTML 태그는 객체이며, 자바스크립트로 접근하고 제어할 수 있다.
  • 이렇게 생성된 하나의 객체를 Node라고 부른다. image image

getElement…

1
2
3
4
5
6
7
document.body.style.backgroundColor = "blue";
// id는 유일
const el = document.getElementById("first");
// 태그는 복수
const pList = document.getElementsByTagName("p");
// 만들어진 p 리스트는 객체형이기 때문에 for...of로 순회할 수 있다.
document.getElementsByClassName;

querySelector

  • querySelectorAll은 모든 요소를, querySelector처음 요소를 가져온다.
1
2
3
4
5
6
7
8
9
document.querySelectorAll(".link");

document.querySelectorAll("#first");
// NodeList [p#first]
document.querySelector("#first");
// <p id="first" ...></p>

// 짝수번 p태그
const pList = document.querySeletorAll("p:nth-of-type(2n)");
  • querySelectorAll로 여러 개의 요소를 저장했지만, 배열로 보이는 유사 객체이기 때문에 배열 메서드를 사용할 수 없다.
  • 그렇기 때문에 배열로 바꿔주는 메서드를 사용해서 배열로 변경 후 사용해야 한다.
1
Array.from(pList);

Node와 Elements

  • querySelectAll을 사용 시, NodeList를 반환하며, getElementsByTagNameHTMLCollecton을 반환한다.
  • 둘 다 유사 배열이기 때문에 같은 요소를 반환하더라도 차이점이 있다.
  • 이는 개발자 도구에서 html태그를 직접 추가하여 작성하면, getElementsByTagName은 바로 반영되어 요소가 추가되지만, NodeList는 한 번 저장된 값을 계속 사용하기 때문에 요소가 추가되지 않는다.
  • parentNodeparentElement를 사용하여 부모 요소를 가져올 수 있다.
1
2
3
4
5
6
document.documentElement;
// <html lang="ko">...</html>
document.documentElement.parentNode;
// #document
document.documentElement.parentElement;
// null
  • 위 코드와 같이 같은 부모 요소를 탐색하는 방법임에도 parentNode#document, parentElementnull이 반환되는 이유는 Elementhtml태그로 이루어진 요소노드만을 반환하기 때문이다.

Node Type

  • 위처럼 Node에는 12가지의 타입이 있다. 노드타입
  • 주요 노드
    • ELEMENT_NODE : <p>,<div>
    • ATTRIBUTE_NODE :