TypeScript에서 DOM 조작/이벤트 처리를 위한 클래스

TypeScript에서 DOM 조작/이벤트 처리를 위한 클래스

이 기사에서는 TypeScript에서 DOM 조작/이벤트 처리를 위해 사용되는 클래스에 대해 설명합니다.

Document 클래스, ElementNodeList 클래스, 그리고 다양한 이벤트 관련 클래스들을 코드 예제를 통해 학습할 수 있습니다.

YouTube Video

TypeScript에서 DOM 조작/이벤트 처리를 위한 클래스

TypeScript에서 DOM 조작 및 이벤트 처리를 위해 주로 문서 객체 모델(DOM) 인터페이스가 사용됩니다. DOM 조작 및 이벤트 처리에서는 표준 JavaScript 클래스와 인터페이스가 사용되지만, TypeScript에서는 타입 정보가 추가되어 더 안전한 작업이 가능합니다.

다음은 DOM 조작 및 이벤트 처리에서 일반적으로 사용되는 클래스와 인터페이스를 설명합니다.

DOM 조작에 사용되는 주요 클래스/인터페이스

Document

Document는 HTML 또는 XML 문서를 나타내는 객체입니다. DOM 트리에 접근하거나 요소를 검색할 때 사용됩니다.

코드 예제
 1// Get the element using getElementById
 2const element = document.getElementById('myElement') as HTMLDivElement | null;
 3if (element) {
 4    element.textContent = 'Hello, TypeScript!';
 5}
 6
 7// querySelector can specify a generic type for more precise typing
 8const button = document.querySelector<HTMLButtonElement>('#myButton');
 9button?.addEventListener('click', () => {
10    console.log('Button clicked!');
11
12    // Create a new element dynamically
13    const newDiv = document.createElement('div');
14    newDiv.textContent = 'New element created!';
15    document.body.appendChild(newDiv);
16});
주요 메서드
  • getElementById는 지정한 id 속성을 가진 요소를 가져옵니다.
  • querySelector는 CSS 선택자를 사용하여 요소를 가져옵니다.
  • createElement는 새로운 HTML 요소를 생성합니다.
코드 설명
  • getElementById를 사용하여 id 속성이 있는 요소를 가져오고 해당 텍스트를 변경하는 코드입니다. 또한, querySelector를 사용해 버튼 요소를 얻고 클릭 이벤트 리스너를 추가합니다. 클릭 시, createElement를 사용하여 새로운 div 요소를 생성하고 이를 메인 콘텐츠에 추가합니다. DOM 작업 시 제네릭과 타입 단언(type assertion)을 사용하여 타입 안전성을 보장합니다.

Element

Element는 DOM 내 개별 HTML 요소를 나타내는 인터페이스입니다. DOM을 조작할 때 가장 일반적으로 사용됩니다.

코드 예제
 1// Use querySelector to manipulate element properties
 2const divElement = document.querySelector<HTMLDivElement>('.myClass');
 3if (divElement) {
 4    // Set innerHTML
 5    divElement.innerHTML = '<strong>Hello with innerHTML!</strong>';
 6
 7    // Set textContent
 8    divElement.textContent = 'Hello with textContent!';
 9
10    // Add a new class
11    divElement.classList.add('newClass');
12
13    // Set a custom attribute
14    divElement.setAttribute('data-role', 'content');
15}
주요 속성과 메서드
  • innerHTML 속성은 요소의 HTML 내용을 설정하거나 가져올 수 있도록 해줍니다.
  • textContent 속성은 요소의 텍스트 내용을 설정하거나 가져올 수 있도록 해줍니다.
  • classList는 클래스를 조작하는 속성으로, 클래스를 추가·제거·토글할 수 있습니다.
  • setAttribute 메서드는 요소에 속성을 설정합니다.
코드 설명
  • 이 코드는 querySelector로 가져온 요소에 innerHTMLtextContent로 내용을 설정하고, classList로 클래스를 추가하며, setAttribute로 커스텀 속성을 설정하는 예제입니다. 제네릭을 사용하여 타입 안전하게 작업이 수행됩니다.

NodeListHTMLCollection

NodeListHTMLCollection은 여러 DOM 요소가 포함된 컬렉션을 나타냅니다. 예를 들어, querySelectorAllNodeList를 반환하며, getElementsByClassNameHTMLCollection을 반환합니다.

코드 예제
 1// NodeList supports forEach iteration
 2const divs: NodeListOf<HTMLDivElement> = document.querySelectorAll('div');
 3divs.forEach(div => {
 4    div.textContent = 'Updated!';
 5});
 6
 7// HTMLCollection is not directly iterable, convert it to an array
 8const spans: HTMLCollectionOf<HTMLSpanElement> =
 9    document.getElementsByClassName('span-item') as HTMLCollectionOf<HTMLSpanElement>;
10Array.from(spans).forEach(span => {
11    span.textContent = 'Changed!';
12});
  • 이 코드는 NodeListforEach로 직접 처리하고, HTMLCollection을 배열로 변환하여 반복하는 방법을 보여줍니다.

이벤트 처리에 사용되는 주요 클래스/인터페이스

Event

Event는 DOM에서 발생하는 모든 이벤트의 기본 클래스입니다. 클릭, 입력, 페이지 로드와 같은 다양한 이벤트는 Event 클래스를 확장합니다.

코드 예제
 1const form = document.querySelector<HTMLFormElement>('#myForm');
 2form?.addEventListener('submit', (event: Event) => {
 3    // target refers to the element that triggered the event (the form)
 4    const target = event.target as HTMLFormElement;
 5
 6    // type shows the kind of event, e.g., "submit"
 7    console.log(`Event type: ${event.type}`);
 8
 9    // preventDefault disables the default form submission
10    event.preventDefault();
11    console.log('Form submission prevented.');
12});
주요 속성과 메서드
  • target 속성은 이벤트가 발생한 요소(EventTarget)를 나타냅니다.
  • type은 발생한 이벤트의 타입(예: click, input)을 나타냅니다.
  • preventDefault 메서드는 이벤트의 기본 동작을 취소합니다.
코드 설명
  • 이 코드는 폼에 submit 이벤트 리스너를 추가하는 방법을 보여줍니다. target은 이벤트가 발생한 폼 요소를 가리키며, type은 이벤트 타입(이 경우 "submit")을 나타냅니다. preventDefault 메서드를 호출하면 페이지 이동이나 새로고침과 같은 기본 폼 제출 동작을 비활성화할 수 있습니다. 대신, 여기서는 출력 로그를 남기는 커스텀 프로세스가 실행됩니다.

MouseEvent

MouseEvent는 마우스 조작과 관련된 이벤트를 나타냅니다. clickmousemove와 같은 마우스 이벤트는 이 클래스를 사용합니다.

코드 예제
1const div = document.getElementById('clickArea');
2if (div) {
3    div.addEventListener('click', (event: MouseEvent) => {
4        console.log(`Clicked at: (${event.clientX}, ${event.clientY})`);
5    });
6}
  • 이 코드는 MouseEvent를 사용해 마우스 좌표를 로그로 출력하는 예시입니다.
주요 속성
  • clientX는 페이지 내에서 마우스 포인터의 X 좌표입니다.
  • clientY는 페이지 내에서 마우스 포인터의 Y 좌표입니다.
  • button은 어떤 마우스 버튼이 눌렸는지를 나타냅니다. 0은 왼쪽 버튼, 1은 가운데 버튼, 2는 오른쪽 버튼을 의미합니다.

KeyboardEvent

KeyboardEvent는 키보드 조작과 관련된 이벤트를 나타냅니다. keydownkeyup 이벤트가 이 범주에 속합니다.

코드 예제
 1document.addEventListener('keydown', (event: KeyboardEvent) => {
 2    // Show the key name (e.g., "Enter", "a")
 3    console.log(`Key pressed: ${event.key}`);
 4
 5    // Show the physical key code (e.g., "Enter", "KeyA")
 6    console.log(`Key code: ${event.code}`);
 7
 8    // Check if Alt/Ctrl/Shift key was pressed
 9    console.log(`Alt pressed: ${event.altKey}`);
10    console.log(`Ctrl pressed: ${event.ctrlKey}`);
11    console.log(`Shift pressed: ${event.shiftKey}`);
12
13    if (event.key === 'Enter') {
14        console.log('Enter was pressed');
15    }
16});
주요 속성
  • keyEntera와 같이 누른 키의 이름입니다.
  • code는 키보드의 각 키에 해당하는 코드입니다.
  • altKey, ctrlKey, shiftKey는 각각 Alt, Ctrl, Shift 키가 눌렸는지 여부를 나타내는 속성입니다.
코드 설명
  • 이 코드는 KeyboardEvent를 사용해 눌린 키의 이름(key), 해당 키 코드(code), 그리고 수정 키(altKey, ctrlKey, shiftKey)가 눌렸는지 로그를 남깁니다. 또한, Enter 키가 눌렸을 때 특별한 동작도 수행합니다.

FocusEvent

FocusEvent는 포커스를 얻거나 잃는 이벤트와 관련이 있습니다. focusblur 이벤트가 이 범주에 속합니다.

코드 예제
 1const inputElement = document.getElementById('myInput');
 2if (inputElement) {
 3    inputElement.addEventListener('focus', (event: FocusEvent) => {
 4        console.log('Input focused');
 5    });
 6
 7    inputElement.addEventListener('blur', (event: FocusEvent) => {
 8        console.log('Input lost focus');
 9    });
10}
  • 이 코드는 FocusEvent를 사용해 입력 필드에 포커스가 생기거나 사라질 때를 감지하고 로그로 출력하는 예시입니다.

TypeScript에서의 타이핑

TypeScript를 사용하면 DOM 조작과 이벤트 처리에서 타입 검사가 향상됩니다. 다음은 TypeScript에서 타입 안전한 DOM 조작과 이벤트 처리 예제입니다.

타입화된 이벤트 리스너

이벤트 리스너를 추가할 때, 이벤트의 타입을 지정하면 타입 검사가 수행되고 잘못된 속성에 접근할 수 없게 됩니다.

1const input = document.querySelector<HTMLInputElement>('#myInput');
2// Event listener with explicit type annotation for safety
3input?.addEventListener('input', (event: Event) => {
4    // event.target is EventTarget, so it needs to be cast to the correct type
5    const target = event.target as HTMLInputElement;
6    console.log(`Current value: ${target.value}`);
7});
  • 이 코드는 타입이 지정된 이벤트 리스너로 input 이벤트를 처리하고, 입력 필드의 현재 값을 안전하게 받아와 출력하는 예시입니다.

제너릭 이벤트 처리

TypeScript에서 제너릭을 사용하여 다양한 유형의 이벤트를 지원하는 제너릭 이벤트 처리를 수행할 수 있습니다.

 1// Generic event handler function
 2function handleEvent<T extends Event>(event: T) {
 3    console.log(`Event type: ${event.type}`);
 4    if (event.target instanceof HTMLElement) {
 5        console.log(`Target element: ${event.target.tagName}`);
 6    }
 7}
 8
 9const input = document.querySelector<HTMLInputElement>('#myInput');
10input?.addEventListener('input', handleEvent);
  • 이 코드는 제네릭을 활용한 범용 이벤트 핸들러의 예시로, 이벤트 타입과 대상 요소의 태그 이름을 로그로 출력합니다.

요약

TypeScript에서는 DOM 조작과 이벤트 처리 중 표준 DOM API에 타입이 적용되어 코드의 안전성과 가독성이 향상됩니다. Document, Element와 같은 클래스와 Event, MouseEvent, KeyboardEvent 등 이벤트 관련 클래스를 활용하여 타입 안전한 개발이 가능합니다. 또한, querySelector<T>() 또는 HTMLCollectionOf<T>를 사용하면 타입 안전한 DOM 조작이 가능합니다.

위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.

YouTube Video