황규진 2024. 7. 10. 14:08

문제 객체 모델

  • 문서 객체 모델(DOM, Document Object Model)은 넓은 의미로 웹 브라우저가 HTML 페이지를 인식하는 방식이고 좁은 의미로는 document 객체와 관련된 객체의 집합.
  • 문서 객체 모델을 사용하면 HTML 페이지에 태그를 추가, 수정, 제거할 수 있음

문서 객체 모델과 관련된 용어 정리

요소(Element)

  • HTML 페이지에 있는 html, head, body, title, h1, div, span 등의 태그를 HTML 언어에서는 요소(element)라고 부름
  • 자바스크립트 언어에서는 HTML 언어에서 요소를 문서 객체(document object)라고 부름
    • 문서 객체를 조작한다는 말은 HTML 요소를 조작한다는 의미
    • 제이쿼리(jQuery) 라이브러리, 리액트(React)와 같은 프레임 워크를 사용하기 때문에 문서 객체 조작이 쉬워짐.

태그(Tag)

<!DOCTYPE html>
<heml>
<head>
	<title>index</title>
	<script></script>
</head>
<body>
	<h1 id = “header”> HEADER </h1>
</body>
</html>
  • 이 태그를 자바스크립트에서 사용할 수 있는 객체로 만들면 그것이 ‘문서 객체‘임
<script>
	window.onload = function( ) {
		var header = document.getElementById(‘header’);
	};
</script>
  • 위 코드에서 header 객체를 ‘문서 객체'라고 부름

요소 노드(Element Node)와 텍스트 노드(Text Node)

  • 요소 노드
    • HTML 태그를 의미
  • 텍스트 노드
    • 요소 노드 안에 들어 있는 글자를 의미

 

문서 객체 만들기

-문서 객체는 텍스트 노드를 갖은 문서 객체와 텍스트 노드를 갖지 않는 문서 객체로 구분

  • 텍스트 노드를 갖는 h1 태그를 만들면서 문서 객체 생성
<body>

</body>

 

  • Body 태그에 동적으로 문서 객체를 생성해서 넣기
    • 텍스트 노드를 갖는 문서 객체를 생성하려면 요소 노드와 텍스트 노드를 생성하고 텍스트 노드를 요소 노드에 붙인 후 body 문서 객체에 연결
<script>
	window.onload = function( ) {
		var header = document.createElement(‘h1’);
		varh textNode = document.createTextNode(‘Hello DOM’);
	};
</script>
  • 부모 객체.appendChild(자식 객체)
  • 위 코드를 실행 했을 때 브라우저 상에 아무 것도 나타나지 않음.
  • 생성한 문서 객체를 body 문서 객체에 연결해야 나타남.
  • 또한 생성한 요소 노드와 텍스트 노드도 연결해야 함
<script>
	window.onload = function( ) {
		var header = document.createElement(‘h1’);
		var textNode = document.createTextNode(‘Hello DOM’);
	// 노드를 연결함.
		header.appendChild( textNode ); // 요소 노드에 텍스트 노드 연결
		document.body.appendChild(header); // body 문서 객체에 생성한 객체 연결
	};
</script>

 

텍스트 노드를 갖지 않는 요소 노드를 만들기

<script>
	window.onload = function( ) {
		var img = document.createElement(‘img’);
		document.body.appendChild(img);
	};
</script>
  • img 태그에 이미지를 넣으려면 scr 속성을 지정해 줘야 함
    <script>
    	window.onload = function( ) {
    		var img = document.createElement(‘img’);
    		img.src = ‘Penguins.jpg’;
    		img.width = 500;
    		img.height = 350;
    		document.body.appendChild(img);
    };
    </script>
    ​

innerHTML 속성을 사용하기

  • 문자열을 선언하고 body 문서 객체의 innerHTML 속성에 넣기만 하면 문서 객체를 생성해 줌
<script>
	window.onload = function( ) {
		var output = ‘’;
		document.body.innerHTML = output;
	};
</script>
  • innerHTML 속성을 사용한 문서 생성
<script>
	window.onload = function( ) {
		var output = ‘’;
		output += ‘<ul>’;
		output += ‘ <li>javaScript</li>’;
		output += ‘ <li>jQuary</li>’;
		output += ‘ <li>Ajax</li>’;
		output += ‘</ul>’;
		document.body.innerHTML = output;
	};
</script>

 

문서 객체 가져 오기

웹 페이지에 있는 HTML 태그를 자바스크립트로 가져 오는 방법

  • Document 객체가 가지고 있는 getElementById(id) 메서드를 이용하여 웹 페이지에 포함된 문서 객체를 가져올 수 있음
    • 한번에 한 가지 문서 객체만 가져올 수 있음. id는 유니크!
<script>
	window.onload = function( ) {
		var header1 = document.getElementById(‘header-1’);
		var header2 = document.getElementById(‘header-2’);
	};
</script>
<body>
	<h1 id = ‘header-1’>Header</h1>
	<h1 id = ‘header-2’>Header</h1>
</body>

변경

<script>
	window.onload = function( ) {
		var header1 = document.getElementById(‘header-1’);
		var header2 = document.getElementById(‘header-2’);
		header1.innerHTML = ‘Ha Ha’;
		header2.innerHTML = ‘^^’;
	};
</script>

  • Document 객체가 가지고 있는 getElementByName(name), getElementByTagName(tagName) 메서드를 이용하여 한 번에 문서 객체를 가져올 수 있음
<!DOCTYPE html>
<html>
<head> <title>Index</title>
<script>
	window.onload = function( ) {
		var headers = document.getElementsByTagName(‘h1’);
	};
</script>
</head>
<body>
	<h1> Header </h1>
	<h1> Header </h1>
</body>
</html>

<script>
	window.onload = function( ) {
		var headers = document.getElementsByTagName(‘h1’);
		headers[0].innerHTML = ‘Header One’;
		headers[1].innerHTML = ‘Header Two’;
	};
</script>

웹 페이지에 있는 HTML 태그를 자바스크립트로 가져 오는 방법

  • Document 객체가 가지고 있는 querySelector(선택자), querySelectorAll(선택자) 메서드를 이용하여 문서 객체를 가져올 수 있음
<!DOCTYPE html>
<html>
<head> <title>Index</title>
<script>
	window.onload = function( ) {
		var header1 = document.querySelector(‘#header-1’);
		var header2 = document.querySelector(‘#header-2’);
	};
</script>
</head>
<body>
	<h1 id = ‘header-1’> Header </h1>
	<h1 id = ‘header-2’> Header </h1>
</body>
</html>
<script>
	window.onload = function( ) {
		var header1 = document.querySelector(‘#header-1’);
		var header2 = document.querySelector(‘#header-2’);

		header1.innerHTML = ‘Header One’;
		header2.innerHTML = ‘Header Two’;
	};
</script>

Document.body 코드를 사용하면 문서의 body 요소를 읽어 들일 수 있음

  • body 요소 외에도 head 요소와 title 요소 등은 다음과 같은 방법으로 읽어 들일 수 있음
document.head
document.title
document.body
<!DOCTYPE html>
<html><head>
	<title></title>
	<script>
		document.addEventListener('DOMContentLoaded', () =>{
			const header = document.querySelector('h1')

			header.textContent = 'HEADERS'
			header.style.color = 'white'
			header.style.background = 'black'
			header.style.padding = '10px'
		})
	</script>
</head>
<body>
<h1></h1>
</body>
</html>

<!DOCTYPE html>
<html><head>
	<title></title>
	<script>
		document.addEventListener('DOMContentLoaded', () =>{
			const headers = document.querySelectorAll('h1')
			headers.forEach( (header) => {
			header.textContent = 'HEADERS'
			header.style.color = 'white'
			header.style.backgroundColor = 'black'
			header.style.padding = '10px'
			})
		})
	</script>
</head>
<body>
<h1></h1> <h1></h1> <h1></h1> <h1></h1>
</body></html>

 

문서 객체의 스타일 조작

  • 문서 객체의 style 속성을 사용하면 해당 문서 객체의 스타일을 변경할 수 있음
<!DOCTYPE html>
<html>
	<head> 
		<script>
			window.onload = function(){
				var header = document.getElementById('header');
				header.style.border = '2px solid black';
				header.style.color = 'orange';
				header.style.backgroundColor = 'brown';
			};
		</script>
	</head>
	<body>
		<h1 id = 'header'> Header</h1>
	</body>
</html>

문서 객체 제거

  • 문서 객체를 제거할 때는 removeChild( child ) 메서드 사용
<!DOCTYPE html>
<html>
<head> <title>Index</title>
<script>
	window.onload = function( ) {
		var willRemove = document.getElementById(‘will-remove’);
		document.body.removeChild( willRemove );
	};
</script>
</head>
<body>
	<h1 id = ‘will-remove’> Header </h1>
</body>
</html>

 

문서 객체를 사용한 시계

<!DOCTYPE html>
<html>
	<head> 
		<script>
			window.onload = function(){
				let clock = document.getElementById('clock');
				setInterval(function(){
					let t = new Date().toLocaleTimeString()
					console.log(t)
				}, 1000);
			};
		</script>
	</head>
	<body>
		<h1 id = 'clock'> </h1>
	</body>
</html>

 

DOMContentLoaded 이벤트

  • DOMConentLoaded는 HTML5부터 추가된 이벤트
<script>
	window.onload = function(){
		const h1 = (text) => `<h1>${text}</h1>`
		document.body.innerHTML += h1('window의 load 이벤트 발생')
	}
</script>

<script>
	document.addEventListener('DOMContentLoaded', () => {
		const h1 = (text) => `<h1>${text}</h1>`
		document.body.innerHTML += h1('DOMContentLeaded 이벤트 발생')
	})
</script>

 

글자 조작 하기

  • innerHTML 속성과 textContent 속성을 사용해서 문서 객체 내부의 글자 조작
<!DOCTYPE html>
<html><head>
	<title></title>
	<script>
			document.addEventListener('DOMContentLoaded', () =>{
				const a = document.querySelector('#a')
				const b = document.querySelector('#b')

				a.textContent = '<h1>textContent</h1>'
				b.innerHTML = '<h1>innerHTML</h1>'
			})
	</script>
</head>
<body>
	<div id="a"></div>
	<div id="b"></div>
</body></html>

 

속성 조작하기

<!DOCTYPE html>
<html><head>
	<title></title>
	<script>
		document.addEventListener('DOMContentLoaded', () =>{
			const rects = document.querySelectorAll('.rect')
			rects.forEach( (rect, idx) => {
				const width = (idx + 1) * 100
				const src = `http://placekitten.com/${width}/250`
				rect.setAttribute('src', src)
			})
		})
	</script>
</head>
<body>
<img class="rect"><img class="rect"><img class="rect"><img class="rect">
</body></html>