본문 바로가기
Front-End Study/[코딩 자율학습] HTML+CSS+JavaScript

12장_문서 객체 모델과 이벤트 다루기_1

by 코딩기 2023. 12. 7.
728x90
  • 웹 브라우저는 ==문서 객체 모델(DOM)==을 구성하며, HTML 문서의 구성요소를 객체로 인식

  • 문서 객체 모델이 생성되는 방식
    문서 객체 모델은 기본적으로 트리 구조(DOM 트리)

<!-- 일렬 구성 예시 -->
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title>
</head><body></body></html>
객체 하위의 '노드'로 구성
 1. 꼭대기의 루트 노드(html 태그)
 2. 루트 노드의 하위 노드(head 태그, meta 태그, title 태그, body 태그)
  - 서로 부모, 형제, 자식 등의 관계로서 성립됨
  • 노드 타입 살펴보기
    DOM 트리의 노드들도 다양한 종류가 존재하며, 각기 다른 작업을 수행
타입 설명
문서 노드(Node.DOCUMENT_NODE) 최상위 document 객체 노드 타입
요소 노드(Node.ELEMENT_NODE) h1, p 태그와 같은 요소 노드 타입
속성 노드(Node.ATTRIBUTE_NODE) href, src와 같은 속성 노드 타입
텍스트 노드(Node.TEXT_NODE) 텍스트 해당 노드 타입
주석 노드(Node.COMMENT_NODE) 주석 해당 노드 타입

CSS 관련 노드 타입은 존재X

12.2 노드 선택하기

  • 속성으로 노드 선택하기
    타입 구분 없이 전체적인 노드 탐색 & 요소 노드만 탐색
// 예시
document.firstChild; // <!DOCTYPE html> (전체 노드 중 첫째 노드 탐색)
docunment.firstElementChild // <html> (요소 노드 중 첫째 노드 탐색)
document.childNodes[1].firstElementChild.nextElemnetSibling // 연속 사용 가능
  • 메서드로 노드 선택하기
    요소 노드를 바로 선택 가능한 메서드 활용
// 속성값과 태그명 사용 - get 메서드
// 예시
<body>
	<p id = "child1">...</p>
	<p class = "child2">...</p>
	<p class = "child2">...</p>
	<script>
		const el = document.getElementById("child1"); // child1인 요소노드 선택
		const el = document.getElemenmtByClassName("child2"); // child2인 요소 노드 선택
		const el = document.getElementByTagName("p"); // p인 요소 노드 선택
	</script>
</body>
// getElementById를 제외한 두 메서드는 '객체유사배열'이므로 []를 통해 인덱스 사용 가능

// CSS 선택자 사용하기 - query 메서드
// 예시
<body>
	<div class = "box-1">
		<p class = "text">...</p>
		<p class>...</p>
	</div>
	<div class = "box-2">
		<p class>...</p>
		<p class>...</p>
	</div>
	<script>
		const el = document.querySelector(".box-1"); // box-1인 요소 노드 선택
		const el = document.querySelectorAll(".box-1", ".text"); // box-1의 자식 선택
	</script>
</body>

12.3 노드 조작하기

  • 콘텐츠 조작하기
    요소 노드 타입 조작 시 사용 속성
속성 설명
textContent 요소 노드의 모든 텍스트에 접근
innerText 요소 노드의 텍스트 중 웹 브라우저에 표시되는 텍스트에만 접근
innerHTML 요소 노드의 텍스트 중 HTML 태그를 포함한 텍스트에만 접근
<!-- 예시 -->
<p id = "title">Hello, <span style = "display:none">JavaScript!</span></p>
document.getElementById("title").textContent; // Hello, JavaScript!
document.getElementById("title").innerText; // Hello,
document.getElementById("title").innerHTML; // Hello, <span style = "display:none">JavaScript!</span>

// 속성에 값 할당 시 노드 콘텐츠 변경 가능
<p id = "text"></p>
document.querySeclector("p").textContent = `<strong>TEXT</strong> 속성`;
document.querySeclector("p").innerText = `<strong>TEXT</strong> 속성`;
document.querySeclector("p").innerHTML = `<strong>TEXT</strong> 속성`;
// textContent와 innerText는 전부 텍스트로 취급, innerHTML은 태그를 인식하여 적용
  • 스타일 조작하기
    style 속성으로 CSS 지정 가능
//  기본 형식
<노드>.style.<CSS 속성명> = <속성값>;

// 예시
<p id = "text">text</p>
<script>
	const el = document.querySelector("p"); // 노드 선택
	pel.style.color = "red"; // 노드 해당 CSS 스타일 지정
</script>

CSS 속성 중 '-'기호가 포함된 속성은 - 연산자로 인식하여 오류, 카멜 표기법으로 작성

  • 클래스 속성 조작하기
    class 속성 조작을 통해 스타일 적용
// 기본 형식
<노드>.classList.add("classs 속성값"); // 추가
<노드>.classList.remove("classs 속성값"); // 삭제
<노드>.classList.toggle("classs 속성값"); // 추가와 삭제 반복

// 예시
<style>
	.red-color{
		color:red;
	}
	.fz20{
		font-size:20px;
	}
</style>
...
<p id = "text">text</p>
<script>
	const el = document.querySelector("#text"); // 노드 선택
	pel.classList.add("red-color");
	pel.classList.add("fz20"); // <p id = "text" class = "red-color fz20">text</p>
	pel.classList.remove("red-color"); // <p id = "text" class = "fz20">text</p>q
	pel.classList.toggle("fz20"); // class = "fz20"값이 추가, 삭제를 반복
</script>
// 한번에 추가도 가능
pel.classList.add("red-color", "fz20"); // 위와 동일qqqq
  • 데이터 속성 조작하기
    사용자가 원하는 속성을 추가하는 data-*를 조작
// 예시
<button data-cnt = "10">가방 구매</button>
<button data-cnt = "0">신발 구매</button>
<script>
	const buttonELS = document.querySelectorAll("button");
	buttonELS.forEach(el) => {
		console.log(el.dataset.cnt); // 10, 0 출력
	}
</script>

// 속성에 값 할당 시 속성값 변경 가능
  • 메서드로 속성 조작하기
    메서드를 사용해 모든 속성 전체 조작
메서드 형식 설명
<노드>.getAttribute(“속성명”); 속성값 가져오기
<노드>.setAttribute(“속성명”, “속성값”); 속성값 설정하기
<노드>.removeAttribute(“속성명”); 속성값 삭제하기
<a href = "..." class = "red";>...</a>
<script>
	const aEl = document.querySelector("a");
	const href = aEl.getAttribute("href");
	console.log(href); // 속성 출력
	aEl.setAttribute("href", "https://coding-woogi.tistory.com/"); // 속성값 변경
	aEl.innerText = "내 블로그"; // a태그 요소의 텍스트 값 변경
	aEl.removeAttribute("class"); // class 속성 삭제
</script>

12.4 노드 추가/삭제하기

  • 노드 추가하기
    메서드를 사용해 DOM 트리에 새로운 노드 추가
- 노드 생성
 createElement() : 요소 노드 생성
 createTextNode() : 텍스트 노드 생성
 createAttribute() : 속성 노드 생성

- 노드 연결
 <기준 노드>.appendChild(<자식 노드>) : 기존 노드에 자식 노드 연결
  <기준 노드>.setAttributeNode(<자식 노드>) : 기준 노드에 속성 노드 연결
// 예시
<!DOCTYPE html>
<head>
    <title>Document</title>
</head>
<body>
	<script>
		// 요소 노드 추가
		const aEl = document.createElement("a"); // a태그 생성
		document.body.appendChild("aEl"); // body 태그에 자식으로서 a태그 연결
		// 텍스트 노드 추가
		const txtEl = document.createTextNode("내 블로그"); 
		document.querySelector("a").appendChild(txtEl); // a태그에 텍스트 노드 연결
		// 속성 노드 추가
		const hrefAttr = document.createAttribute("href");
		hrefAttr.value = "https://coding-woogi.tistory.com/";
		document.querySelector("a").setAttributeNode(hrefAttr);
	</script>
</body>
</html>
  • 노드 삭제하기
    메서드를 사용해 DOM트리 기존 노드 삭제
// 기본 형식
<부모 노드>.removeChild(<자식 노드>);

// 예시
<body>
	<p>text</p>
	<a href = "https://coding-woogi.tistory.com/">내 블로그</p>
	<script>
		const pEl = document.querySelector("p");
		pEl.parentNode.removeChild(pEl); // 부모 노드 접근 후 자식 노드 삭제
		const childNodes = document.body.childNodes;
		childNodes.forEach((node) => {
			node.parentNode.removeChild(node); // 트리 순회 후 a태그 해당 노드 삭제식
		})
	</script>