Classes Used for DOM Manipulation/Event Handling in TypeScript
In this article, we will explain the classes used for DOM manipulation/event handling in TypeScript.
You can learn about the Document class, the Element and NodeList classes, and various event-related classes through code examples.
YouTube Video
Classes Used for DOM Manipulation/Event Handling in TypeScript
For DOM manipulation and event handling in TypeScript, the Document Object Model (DOM) interfaces are primarily used. In DOM manipulation and event handling, standard JavaScript classes and interfaces are used, but in TypeScript, type information is added to them, enabling safer operation.
The following describes the classes and interfaces commonly used in DOM manipulation and event handling.
Main Classes/Interfaces Used for DOM Manipulation
Document
Document is an object representing HTML or XML documents. Used to access the DOM tree or search for elements.
Code Example
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});Main Methods
getElementByIdretrieves an element with the specifiedidattribute.querySelectorretrieves an element using a CSS selector.createElementcreates a new HTML element.
Code Explanation
- This code retrieves an element with an
idattribute usinggetElementByIdand changes its text. It also obtains a button element usingquerySelectorand adds a click event listener. On click, it creates a newdivelement usingcreateElementand adds it to the main content. Generics and type assertions are used to ensure type safety during DOM operations.
Element
Element is an interface that represents individual HTML elements in the DOM. It is most commonly used when manipulating the DOM.
Code Example
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}Main Properties and Methods
- The
innerHTMLproperty allows you to set or get the HTML content of an element. - The
textContentproperty allows you to set or get the text content of an element. classListis a property for manipulating classes, allowing you to add, remove, and toggle classes.- The
setAttributemethod sets an attribute on an element.
Code Explanation
- This code shows an example of setting content using
innerHTMLandtextContentfor elements retrieved withquerySelector, adding classes withclassList, and setting custom attributes withsetAttribute. Operations are performed in a type-safe manner using generics.
NodeList and HTMLCollection
NodeList and HTMLCollection represent collections that contain multiple DOM elements. For example, querySelectorAll returns a NodeList, and getElementsByClassName returns an HTMLCollection.
Code Example
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});- This code demonstrates directly manipulating a
NodeListwithforEach, and converting anHTMLCollectionto an array for iteration.
Main Classes/Interfaces Used for Event Handling
Event
Event is the base class for all events that occur in the DOM. Various events such as clicks, inputs, and page loads extend the Event class.
Code Example
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});Main Properties and Methods
- The
targetproperty represents the element (EventTarget) on which the event occurred. typerepresents the type of event that occurred, such asclickorinput.- The
preventDefaultmethod cancels the default action of the event.
Code Explanation
- This code demonstrates how to add a
submitevent listener to a form.targetrefers to the form element where the event occurred, andtypeindicates the event type (in this case,"submit"). By calling thepreventDefaultmethod, you can disable default form submission behaviors such as page navigation or reload. Instead, a custom process—logging output—is executed here.
MouseEvent
MouseEvent represents events related to mouse operations. Mouse events such as click and mousemove use this class.
Code Example
1const div = document.getElementById('clickArea');
2if (div) {
3 div.addEventListener('click', (event: MouseEvent) => {
4 console.log(`Clicked at: (${event.clientX}, ${event.clientY})`);
5 });
6}- This code is an example of using
MouseEventto log the mouse coordinates.
Main Properties
clientXis the X coordinate of the mouse pointer within the page.clientYis the Y coordinate of the mouse pointer within the page.buttonindicates which mouse button was pressed.0is the left button,1is the middle button, and2is the right button.
KeyboardEvent
KeyboardEvent represents events related to keyboard operations. keydown and keyup events fall under this category.
Code Example
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});Main Properties
keyis the name of the pressed key, such asEnterora.codeis the code corresponding to a key on the keyboard.altKey,ctrlKey, andshiftKeyare properties that indicate whether theAlt,Ctrl, orShiftkey was pressed.
Code Explanation
- This code uses
KeyboardEventto log the name of the pressed key (key), its corresponding key code (code), as well as whether modifier keys (altKey,ctrlKey,shiftKey) were pressed. It also performs a special action when theEnterkey is pressed.
FocusEvent
FocusEvent relates to events of gaining or losing focus. focus and blur events fall under this category.
Code Example
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}- This code is an example of using
FocusEventto detect and log when an input field gains or loses focus.
Typing in TypeScript
When using TypeScript, type checking in DOM manipulation and event handling is enhanced. Below are examples of type-safe DOM manipulation and event handling in TypeScript.
Typed Event Listeners
When adding event listeners, specifying the type of the event performs type checking and prevents access to incorrect properties.
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});- This code is an example of using a typed event listener to handle input events and safely obtain and log the current value of an input field.
Generic Event Handling
Using generics in TypeScript, you can perform generic event handling that supports various types of events.
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);- This code is an example of a generic event handler using generics, which logs the event type and the tag name of the target element.
Summary
In TypeScript, types are applied to standard DOM APIs during DOM manipulation and event handling, enhancing code safety and readability. By utilizing classes such as Document and Element, and event-related classes like Event, MouseEvent, and KeyboardEvent, type-safe development is possible. Additionally, using querySelector<T>() or HTMLCollectionOf<T> enables type-safe DOM manipulations.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.