몰입하며 나아가는 개발이란

Language/JavaScript

JavaScript 구조 접근 방법 DOM(Document Object Model )

류하을 2020. 1. 10. 21:07

DOM이란?

DOM은 BOM(:Browser Object Model)에 속해있는 구조이며,

Document Object Model로 풀어 쓸 수 있으고, 직역을 하면 문서 객체 모델이라고한다.

BOM(:Browser Object Model)의 최상위 객체는 window라는 객체이며, DOM은 window객체의 하위 객체 이기도 하다.

즉, HTML문서를 객체화 하여 구조로 만들고 접근할 수 있는 방법을 제공한다.

DOM의 구조는 Tree 형식의 자료구조를 따라가며,

하나의 root node에서 퍼져나가는 방식이므로 tree 자료구조를 이해한다면 쉽게 이해 할 수 있다.


DOM의 목적

DOM을 사용하게되면 문서를 객체화하여 구조를 이해할 수 있어 쉽게 접근이 가능하게되고,

해당 객체에 접근을 하게되면 수정하는것도 손쉽게 가능하므로,

document를 쉽고 빠르게 접근하기 위함에 목적이 있다고 볼 수 있다.


DOM으로 해석하기

<!DOCTYPE html>
<html>
<head>
	<title>DOM Tutorial</title>
</head>
<body>
	<h1>DOM Lesson one</h1>
	<p>Hello world!</p>
</body>
</html>

위의 HTML은 다음과 같이 읽힐 수 있다 :

<html>이 하나의 root node로 시작되며, <html>은 parents(부모)가 없다.

<html>은 <head>와 <body>의 parent(부모)이다.

<head>는 <html>의 첫번째 child(자녀)이다.

<body>는 <html>의 마지막 child(자녀)이다.

 

그리고,

<head>는 하나의 child(자녀) <title>을 갖고있다.

<title>은 하나의 child(자녀) (a text node): "DOM Tutorial"을 갖고있다.

<body>는 두 child(자녀) <h1>, <p>를 갖고있다.

<h1>은 하나의 child(자녀):  "DOM Lesson one" 을 갖고있다.

<p>는 하나의 child(자녀): "Hello world!"를 갖고있다.

<h1> 과 <p> 는 siblings(형제)이다.

 

DOM을 어렵게 다가가면 어려울수 있으나,

이렇게 풀어나가면 tree 자료구조를 따라간다는것을 한번에 파악 할 수 있으므로,

천천히 읽어보는것이 좋다.


JavaScript로 DOM 사용하기

DOM을 쉽게 이해하는것은 코드 그대로 읽는것이 방법이 빠르다.

아래 코드를 나열하고 DOM을 사용한 부분을 해석을 하는 방법으로 접근해보자.

DOM 해석 1 [.getElementById("id")]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1 id="intro">인트로</h1>
 
<p id="demo">안녕하세요</p>

<button onclick="myFunction()">Click Me!</button> 

<script>
function myFunction() {
	var myText = document.getElementById("intro").childNodes[0].nodeValue;	// 인트로
	document.getElementById("demo").innerHTML = myText;	
}
</script>

</body>
</html>

 

함수 myFunction()에서
var myText = document.getElementById("intro").childNodes[0].nodeVlaue;는

읽히는 그대로 "intro"아이디를 갖는 0번째 자녀 노드의 벨류를 myText에 담는 getter 역할을 하고 있으며,

document.getElementById("demo").innerHTML = myText; 부분은

"demo"아이디를 갖는 객체에 myText를 HTML 형식으로 담는 setter 역할을 하고 있다.


DOM 해석 2 [.innerHTML]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<p>Hello World!</p>

<div>
	<p>The DOM is very useful!</p>
	<p>This example demonstrates the <b>document.body</b> property.</p>
</div>

<button onclick="myFunction()">Click Me!</button> 

<script>
function myFunction() {
	alert(document.body.innerHTML);
}
</script>


</body>
</html>

함수 myFunction() 에서

alert 창을 활성화 시키는데 해당 알람은 document.body.innerHTML 내용을 담고있다.

즉, 이 html 파일을 실행하여, Click Me! 버튼을 누르면

<p>Hello World!</p>

<div>
	<p>The DOM is very useful!</p>
	<p>This example demonstrates the <b>document.body</b> property.</p>
</div>

<button onclick="myFunction()">Click Me!</button> 

<script>
function myFunction() {
	alert(document.body.innerHTML);
}
</script>

이 코드가 alert 창으로 그대로 나오게 된다.


DOM 해석 3 [.getElementsByIdTagName("tagName")]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<p>Hello World!</p>

<p>The DOM is very useful!</p> 

<p id="demo"></p>

<button onclick="myFunction()">Click Me!</button> 

<script>
function myFunction() {
	var myNodelist = document.getElementsByTagName("p");
	document.getElementById("demo").innerHTML =
		"The innerHTML of the second paragraph is: " +
				myNodelist[1].innerHTML;
}
</script>

</body>
</html>

처음에 <p id="demo">태그에는 아무 내용도 들어가있지 않고, Click Me! 버튼을 누름과 동시에

The innerHTML of the second paragraph is: The DOM is very useful! 이라는 <p> 태그가 생성이 된다.
즉, 해석1 부분과 동일하게 getter setter 개념을 적용하여 "demo" 아이디를 갖고있는 태그에 해당 내용을 담을 수 있으며, 여기서 주목해야할것은 myNodelist[1].innerHTML 부분이다.

myNodelist[1]은 <p>The DOM is very useful!</p>를 가르키고 있으며, innerHTML으로 인해 "he DOM is very useful!"만을 담게 된다.


DOM 해석 4 [.createElement(" ")], [.createTextNode(" ")], [appendChild( )]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<div id="div1">
	<p id="p1">This is a paragraph.</p>
	<p id="p2">This is another paragraph.</p>
</div>

<button onclick="myFunction()">Click Me!</button> 

<script>
function myFunction() {
	var para = document.createElement("p");
	var node = document.createTextNode("This is new.");
 	para.appendChild(node);

	var element = document.getElementById("div1");
	element.appendChild(para);
}
</script>

</body>
</html>

var para = document.createElement("p"); 부분은 <p>태그 요소를 생성하며,

var node = document.createTextNode("This is new."); 부분은 "This is new"라는 text 요소를 생성한다.

그리고 다음에 보여지는 para.appendChild(node); 를 통하여 <p>태그에 "This is new" 요소를 더하고,

 

var element = document.getElementById("div1");

element.appendChild(para);를 통해 생성된 <p>This is new</p>를 div1의 요소값에 추가하게된다.

 

removeChild();과 replaceChild( , );도 append와 동일하게 사용된다.


DOM 해석 5 [.childNodes.length]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<style>
div {
    border: 1px solid black;
    margin: 5px;
}
</style>

</head>
<body>

<p>아래의 div 요소에 몇 개의 자식 노드가 있는지 알아 보려면 버튼을 클릭하십시오.</p>

<button onclick="myFunction()">Try it</button>

<!-- 
<div id="myDIV"> 0					
  <p> 1 </p> 2
  <p> 3 </p> 4
</div>
 -->

<div id="myDIV">					
  <p>First p element (index 1)</p>
  <p>Second p element (index 3)</p>
</div>

<p><strong>Note:</strong> 요소 내부의 공백은 텍스트로 간주되고 텍스트
노드로 간주됩니다. 이 예에서 DIV의 인덱스 0, 2 및 4는 텍스트 노드입니다.</p>

<p id="demo"></p>

<script>
function myFunction() {
    var c = document.getElementById("myDIV").childNodes.length;
    document.getElementById("demo").innerHTML = c;  	//	--> 5
    /* document.getElementById("myDIV").childNodes[1].innerHTML = "Hello"; */
    /* alert(document.getElementById("myDIV").childNodes[1].innerHTML); */
}
</script>


</body>
</html>

var c = document.getElementById("myDIV").childNodes.length; 부분에서 "myDIV" 아이디를 가진 요소의 자녀 길이를 갖고 오게되며, 특이하게도 자녀는 총 5를 갖게된다. 위 주석문에 표기가 되어있지만 다시보자면,

<div id="myDIV"> 0					
  <p> 1 </p> 2
  <p> 3 </p> 4
</div>

이렇게 0부터 4까지 해당 childNode가 구성이 되어있음을 확인 할 수 있다.


DOM 해석 6 [.nextSibling]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<p>Example list:</p>

<ul><li id="item1">Coffee (first li)</li><li id="item2">Tea (second li)</li></ul>

<p>단추를 클릭하여 첫 번째 목록 항목의 다음 형제에 대한 HTML 콘텐츠를 가져옵니다.</p>

<button onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> 요소 내부의 공백은 텍스트로 간주되고 텍스트 노드로 간주됩니다.</p>

<p>두 개의 li 요소 사이에 공백을 추가하면 결과가 "undefined(정의되지 않음)"이됩니다.</p>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("item1").nextSibling.innerHTML; 
    document.getElementById("demo").innerHTML = x;	//<-- Tea (second li)
}
</script>

</body>
</html>

var x = document.getElementById("item1").nextSibling은 item 다음 요소인

<li id="item2">Tea (second li)</li> 를 가르키며, .innerHTML로 해당 text 내용만 가져오는것을 확인 할 수 있다.

 

.previousSibling 도 동일하게 사용된다.


DOM 해석 7 [.nodeName]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<p id="myP">단추를 클릭하여 이 요소의 노드 이름을 가져옵니다.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myP").nodeName;
    document.getElementById("demo").innerHTML = x;	//<-- p
}
</script>

</body>
</html>

var x = document.getElementById("myP").nodeName; 은 "myP" 아이디를 갖고 있는 태그의 이름을 가르키며,

"demo" 아이디를 가진 태그에 해당 내용을 seting 하여 확인할 수 있다.


 

'Language > JavaScript' 카테고리의 다른 글

Java Script 란?  (0) 2020.01.06