DOM에 대하여

2022. 9. 2. 21:31Frontend

DOM 이란?

공식문서에서는 DOM 이란 HTML, XML 프로그래밍을 위한 인터페이스 정도로 묘사하고 있다. HTML 문서는 여러개의 DOM들의 Tree 형태로 구성되고 있다.

DOM 에 어떻게 접근할 수 있을까?

일단 DOM은 프로그래밍 언어에 독립적이다. 즉 어떤 언어로도 DOM을 다룰 수 있다. 하지만 주로 Javascript 를 이용한다.

DOM의 대표적인 인터페이스는 무엇이 있을까?

Node는 여러 가지 DOM 타입들이 상속하는 인터페이스이며 그 다양한 타입들을 비슷하게 처리할 수 있게 한다.

DOM들을 트리화하여 관리하기 위해 childNodes(), firstChild, lastChild nextSibling parentNode 같은 속성들과
appendChild(), insertBefore(), getRootNode(), removeChild() 같은 메소드를 제공한다.

nodeType() method 에 의해 node 가 실제 어떤 type을 갖고 있는지 알 수있다.

노드는 정말 많은 Type의 인터페이스들에 의해 상속됨을 알 수 있다.

Element는 Document 안의 모든 객체가 상속하는 제일 범용적인 기반 클래스로 공통 메소드속성만 가지고 있다. Element는 Node를 상속하고 있다 HTML tag들(html, body, h1 등..)은 element 의 인스턴스이다.
innerHtml, id, attributes 의 속성들이나 querySelector(v), addEventListener(v) 같은 메소드들을 사용할 수 있다.

Element는 Node를 상속하고 있으므로 Node의 속성과 메소드 또한 사용할 수 있다!

DOM 의 생성 및 추가

example1

// h1 element 생성
var heading = document.createElement("h1");

// text node 생성
var heading_text = document.createTextNode("Big Head!");

// text node를 h1 element의 child 로 삽입
heading.appendChild(heading_text);

// body에 h1 element 삽입
document.body.appendChild(heading);

example2

코드

<!DOCTYPE html>
<html>
<body>
<h1>The Element Object</h1>
<h2>The insertBefore() Method</h2>

<ul id="myList">
  <li>Coffee</li>
  <li>Tea</li>
</ul>

<script>
// Create a "li" element:
const newNode = document.createElement("li");
// Create a text node:
const textNode = document.createTextNode("Water");
// Append text node to "li" element:
newNode.appendChild(textNode);

// Insert before existing child:
const list = document.getElementById("myList");
list.insertBefore(newNode, list.children[0]);
</script>

</body>
</html>

결과

The Element Object
The insertBefore() Method

Water
Coffee
Tea

이벤트 등록

Syntax

addEventListener(type, listener);
addEventListener(type, listener, options);
addEventListener(type, listener, useCapture);

Example

function f1() {
   // some logics for changing input type
}

function f2(param1)

x.addEventListener('click', f1)
y.addEventListener('click', () => {f2(myParam)})

HTML String 에서 Node로 변환

&lttemplate> tag는 코드의 템플릿을 저장할 수 있는 tag이다.
아래와 같이 HTML string(&lttr> 로 시작하는...) 을 node로 바꿔주는 예시를 보자.

function htmlToElem(html) {
  let temp = document.createElement('template');
  html = html.trim(); // Never return a space text node as a result
  temp.innerHTML = html;
  return temp.content.firstChild;
}
let td = htmlToElem('<td>foo</td>'),
  div = htmlToElem('<div><span>nested</span> <span>stuff</span></div>');
alert(td);
alert(div);

출처

mdn

https://www.w3docs.com/snippets/javascript/how-to-create-a-new-dom-element-from-html-string.html

'Frontend' 카테고리의 다른 글

HTML Layout 만들기 (flexbox)  (0) 2022.08.31