Web/JavaScript

자바스크립트 DOM & EVENT #1 노드에 접근하기

ansui 2023. 8. 20. 17:23

#1 노드에 접근하기


< DOM >

DOM: Document Object Model (문서 객체 모델)

- html문서의 각 요소들을 트리 형식으로 표현

- 개발자는 js를 이용하여 이를 수정할 수 있다.

- Document를 제외한 최상단의 노드: html

- 모든 html 태그 = 객체 → JS로 접근하고 제어 가능!

 

Document
Root element: <html>
Element: <head> Element: <body>
Element: <title> Attribute: "href" Element: <a> Element: <h1>
Text:
"My Title"
  Text:
"My Link"
Text:
"My Header"

 

 

< 예시 1 >

document.documentElement;

document.head;

document.body;

//body 스타일 출력 & 수정 가능
document.body.style;

//body 스타일 불투명도 = 0으로 수정
document.body.style.opacity = '0';

//출력 결과
<html lang="ko">
<head>...</head>
<body>...</body>
</html>

<head>...</head>

<body>...</body>

< 예시 2 >

//해당 아이디 접근
const el = document.getElementById('first')
el;

//해당 클래스 접근
const cl = document.getElementsByClassName('link')
cl;

//해당 태그 접근
const pList = document.getElementsByTagName('p')
pList;

//for문을 이용하여 모든 p태그에 스타일 적용하기
for (p of pList) {
  p.style.fontSize='20px';
  p.style.opacity = String(Math.random());
}

//querySelector 이용하여 아이디 및 클래스 접근
document.querySelector('#first'); //제일 처음 한개만
document.querySelectorAll('#first'); //전부
document.querySelectorAll('.link'); //전부

//출력 결과
<p id="first">...<p>

[a.link, a.link, a.link]

[p#first, p#second, p, p]

<p id="first">...<p>
[p#first]
[a.link, a.link, a.link]

< 예시 3 >

document.questySelector('h3:nth-of-type(2)');

//출력 결과
<h3>B</h3>

//2번째 p를 찾아 색상 변경
document.questySelector('h3:nth-of-type(2)').style.color = 'red';

//for문을 이용하여 모든 p에 style 적용
for (p of pList) {
  p.style.backgroundColor = #000;
  p.style.color = '#fff';
}

*출력 시 Array가 아니라 NodeList로 출력.

- NodeList는 literable한 Collection.

- index를 통해 접근 가능!

- length 사용 가능

- Array가 아니므로 push(), pop(), filter(), join() 사용 불가능

예) pList[1]; pList.length;

 


코딩앙마님의 유튜브 강의 "자바스크립트 DOM & EVENT"를 참고하여 작성하였습니다.