DOM Manipulation in TypeScript
This article explains DOM manipulation in TypeScript.
You will learn how to manipulate DOM elements, and how to add or remove elements from the DOM tree through code examples.
YouTube Video
DOM Manipulation in TypeScript
DOM manipulation in TypeScript is performed similarly to JavaScript, but TypeScript provides type checking, making operations safer. The DOM (Document Object Model) is an object model used to manipulate HTML and XML documents programmatically. It allows you to access pages displayed in the browser, add or remove elements, or change styles.
Let's introduce the basic methods for manipulating the DOM using TypeScript.
Obtaining DOM Elements
Use the document
object to get HTML elements. The following methods are commonly used:.
document.getElementById
document.getElementById
gets the element with the specified ID attribute.`.
1// Type is HTMLElement | null
2const element = document.getElementById('myElement');
3if (element) {
4 console.log(element.innerHTML);
5}
document.getElementById
retrieves the element with the specified ID and allows you to access its content if it exists.`.
document.querySelector
document.querySelector
retrieves the first element that matches the CSS selector.`.
1// Type is Element | null
2const element = document.querySelector('.myClass');
3if (element) {
4 console.log(element.textContent);
5}
document.querySelector
retrieves the first element that matches the specified CSS selector and allows you to access its content if it exists.`.
document.querySelectorAll
document.querySelectorAll
retrieves all elements that match the CSS selector.`.
1// Type is NodeListOf<HTMLDivElement>
2const elements = document.querySelectorAll('div');
3elements.forEach((el) => console.log(el.innerHTML));
document.querySelectorAll
retrieves all elements that match the specified CSS selector and allows you to access their content through iteration.`.
Element Type Assertion
In TypeScript, asserting the type of an element explicitly allows you to use more specific methods and properties.
1const inputElement = document.getElementById('myInput') as HTMLInputElement;
2if (inputElement) {
3 console.log(inputElement.value); // Access the value property of the input element
4}
- The
as
keyword is a type assertion operator in TypeScript, used to explicitly tell the compiler to treat a value as a specific type. - In TypeScript, you can use type assertions to treat the retrieved element as a specific type and access properties or methods specific to that type.
Manipulating the DOM
Manipulation of the DOM is performed through the properties of elements. This allows you to flexibly control changes to text or attributes, apply styles, and update displayed content.
-
Changing an Element's Text
You can change the text or HTML of an element using its
textContent
orinnerHTML
.
1const element = document.getElementById('myElement');
2if (element) {
3 element.textContent = 'New Text'; // Set the text content to 'New Text'
4}
- You can use
textContent
orinnerHTML
of an element to change its displayed text or HTML content.
-
Changing an Element's Style
You can modify inline styles using the element's
style
property.
1const element = document.getElementById('myElement');
2if (element) {
3 element.style.color = 'blue';
4 element.style.fontSize = '20px';
5}
- This code retrieves a specific element, changes its text color to blue, and sets the font size to 20px.
-
Changing an Element's Attributes
If you want to change an element's attributes, use
setAttribute
.
1const link = document.querySelector('a');
2if (link) {
3 link.setAttribute('href', 'https://example.com');
4}
- This code changes the
href
attribute of the first link element on the page tohttps://example.com
.
-
Manipulating Element Classes
To add or remove element classes, use the
classList
.
1const element = document.getElementById('myElement');
2if (element) {
3 element.classList.add('active');
4 element.classList.remove('inactive');
5}
- This code adds the
active
class and removes theinactive
class from a specific element.
Adding and Removing DOM Elements
You can also add new elements or remove existing ones. This makes it possible to dynamically change the page structure in response to user actions or the application's state.
-
Creating and Adding New Elements
Use
document.createElement
to create a new element and add it to the DOM.
1const newDiv = document.createElement('div');
2newDiv.textContent = 'New Element'; // Set the text content to 'New Element'
3document.body.appendChild(newDiv); // Add the new element to the body
- This code creates a new
<div>
element, sets its text, and adds it to the page's<body>
.
-
Removing Elements
To remove an element, use the
removeChild
orremove
methods.
1const parentElement = document.getElementById('parentElement');
2const childElement = document.getElementById('childElement');
3if (parentElement && childElement) {
4 parentElement.removeChild(childElement); // Remove the child element
5}
6
7// Alternatively
8const element = document.getElementById('myElement');
9if (element) {
10 element.remove(); // Remove the element itself
11}
- This code shows how to remove a specific child element from its parent and how to remove the element itself directly.
Adding Events
In TypeScript, you can add event listeners to elements to perform actions based on user interactions.
1const button = document.getElementById('myButton');
2if (button) {
3 button.addEventListener('click', () => {
4 console.log('Button was clicked'); // Log when the button is clicked
5 });
6}
- This code adds an event listener that displays a message in the console when the button is clicked.
- By using
addEventListener
, you can listen for and handle various events such as clicks, mouse movements, and keyboard input.
Points to Note for DOM Manipulation in TypeScript
When manipulating the DOM with TypeScript, paying attention to element type definitions and null
checks can help prevent errors and allow you to write robust code.
-
Null Checking
Because a DOM element might not exist, it is recommended to perform a null check before manipulating elements in TypeScript.
-
Explicit Type Assertion
When operating on a specific element (for example, an
HTMLInputElement
), it is common to use an assertion (as
) to specify the type and use element-specific properties such asvalue
.
Keeping these in mind, DOM manipulation with TypeScript allows you to write safer and more predictable code by combining JavaScript's flexibility with TypeScript's type safety.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.