카테고리 없음

JAVASCRIPT DOM이란? ( DOM 함수 초간단 가이드 )

next.js 2023. 11. 26. 23:27

DOM이란?

DOM은 "Document Object Model"의 약자로, HTML이나 XML 문서를 프로그래밍 언어가 이해하고 조작할 수 있는 객체로 표현하는 방법을 제공하는 인터페이스입니다. 간단히 말해서, 웹 페이지의 구조와 내용을 프로그래밍적으로 조작할 수 있게 해주는 도구라고 생각할 수 있습니다.

여기서 "객체"란 프로그래밍에서 데이터나 기능을 추상화한 것을 의미합니다. DOM은 웹 페이지를 트리 구조로 표현하며, 각 요소는 트리의 노드로 표현됩니다. 각 노드는 객체로 간주되어 해당 노드에 대한 정보나 동작을 조작할 수 있게 해줍니다.

간단한 예시로, 다음과 같은 HTML 코드를 생각해보겠습니다:

<!DOCTYPE html>
<html>
<head>
  <title>My Web Page</title>
</head>
<body>
  <h1>Hello, World!</h1>
  <p>This is a paragraph.</p>
</body>
</html>

위의 HTML 코드는 DOM으로 다음과 같이 표현될 수 있습니다

- document
  - html
    - head
      - title
        - "My Web Page"
    - body
      - h1
        - "Hello, World!"
      - p
        - "This is a paragraph."

 

이 구조를 JavaScript를 사용해 조작하고 변경할 수 있습니다.

 

DOM을 다룰 때 사용되는 몇 가지 중요한 함수들은 다음과 같습니다.

 

1. document.getElementById(id)

  • id 속성 값이 일치하는 요소를 반환합니다.
const myElement = document.getElementById("myId");

2. document.querySelector(selector)

  • CSS 선택자를 사용하여 일치하는 첫 번째 요소를 반환합니다.
const myElement = document.querySelector("#myId .myClass");

3. document.createElement(tagName)

  • tagName에 지정한 HTML 태그 요소를 생성합니다.
const myElement = document.createElement("div");
myElement.textContent = "Hello World!";

4. element.appendChild(newChild)

  • newChild 요소를 자신의 하위 요소로 추가합니다.
const myParent = document.getElementById("myParent");
const myChild = document.createElement("div");
myChild.textContent = "Hello World!";
myParent.appendChild(myChild);

5. element.removeChild(child)

  • child 요소를 자신의 하위 요소에서 제거합니다.
const myParent = document.getElementById("myParent");
const myChild = document.getElementById("myChild");
myParent.removeChild(myChild);

6. element.addEventListener(type, listener[, options])

  • 이벤트 타입에 대한 리스너 함수를 등록합니다.
const myButton = document.getElementById("myButton");
myButton.addEventListener("click", function() {
  console.log("Button clicked!");
});

7. element.removeEventListener(type, listener[, options])

  • 이벤트 타입에 대한 리스너 함수를 제거합니다.
const myButton = document.getElementById("myButton");
const myFunction = function() {
  console.log("Button clicked!");
};

myButton.addEventListener("click", myFunction);
myButton.removeEventListener("click", myFunction);

 

이 함수들을 통해 DOM을 다룰 수 있고, 이를 활용하여 웹 페이지의 동적인 부분을 조작하거나 사용자와의 상호작용을 처리할 수 있습니다.