티스토리 뷰

DOM이란 무엇일까?

DOM(Document Object Model)은 XML이나 HTML같은 웹 문서의 정보를 담고 있는 인터페이스입니다. 우리는 DOM에 있는 문서의 구조부터 스타일, 내용 등을 변경할 수 있습니다. DOM의 전제는 HTML 코드가 담긴 페이지를 문서(Document)라고 한다는 것입니다.

 

출처: 위키백과

 

 

DOM에 접근하고 조작하기

JavaScript로 DOM에 접근하거나 조작할 수 있습니다. HTML 요소나 속성, CSS 스타일을 변경하고, HTML 이벤트를 추가하여 적절한 반응을 하도록 합니다.

 

JS로 DOM에 접근하기

const form = document.querySelector("form");
const input = form.querySelector("input");

1. document에 있는 form element를 form 변수로 가져온다.

2. form element 안에 있는 input element를 input 변수로 가져온다.

 

JS로 이벤트 추가하기

const handleSubmit = (event) => {
  event.preventDefault();
  addList();
};

form.addEventListener("submit", handleSubmit);

위에서 가져온 form element에 submit 이벤트를 추가하고, 이벤트가 발생하면 handleSubmit 함수를 실행하여 반응한다.

 

JS로 HTML 요소나 속성 변경하기

const addList = () => {
  const div = document.createElement("div");
  const span = document.createElement("span");

  span.innerText = "리스트 추가하기";
  div.className = "todo-list";
  div.append(span);
};

1. createElement() 함수로 element를 생성한다

2. innerText로 태그 안의 값을 설정한다.

3. className으로 class 값을 설정한다.

4. append() 함수로 div element에 span element를 넣는다.

 

 

<참고>

 

Introduction to the DOM - Web APIs | MDN

The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web. This guide will introduce the DOM, look at how the DOM represents an HTML document in memory and how to use APIs to

developer.mozilla.org

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함