Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript DOM Manipulation

Learn how to use TypeScript to select HTML elements, update webpage content, handle events, modify CSS styles, and work with user input.

Learning objective: Understand the Document Object Model (DOM), element selection, text and HTML manipulation, event handling, input access, and type safety.

1. What Is the DOM?

DOM stands for Document Object Model. The browser represents an HTML document as a tree of objects. JavaScript and compiled TypeScript can use the DOM APIs to read and modify webpage elements.

TypeScript adds type checking when working with these browser APIs. For example, it helps identify whether an element is an input, a button, or a regular HTML element.

📄
HTML Document

Contains headings, paragraphs, buttons and inputs.

🌳
DOM Tree

The browser represents elements as objects.

💻
TypeScript Code

Selects elements and updates the webpage.

Remember: Browsers execute JavaScript, not TypeScript source directly. TypeScript must be compiled to JavaScript before it runs in a normal browser setup.

2. Selecting HTML Elements

TypeScript can select elements by ID, class, or CSS selector using methods provided by the DOM.

HTML

<h2 id="heading">Welcome to CIIT</h2>

<p class="description">Learn TypeScript</p>

<button id="submitButton">Submit</button>

TypeScript

const heading = document.getElementById("heading");

const description = document.querySelector(".description");

const button = document.getElementById("submitButton");

console.log(heading);
console.log(description);
console.log(button);

Important DOM Methods

Method Purpose Return Type
getElementById() Select an element by ID. HTMLElement | null
querySelector() Select the first matching CSS selector. Element | null
querySelectorAll() Select all matching elements. NodeListOf<Element>
getElementsByClassName() Select elements by class name. HTMLCollectionOf<Element>
Important: Element selection can return null. Check that an element exists before accessing its properties. Make sure the script executes after the relevant HTML elements have been parsed.

3. Changing Text Content

Use textContent to read or update the text inside an element. It treats the supplied value as text, rather than parsing it as HTML.

HTML

<h2 id="message">Old Message</h2>

TypeScript

const message = document.getElementById("message");

if (message) {
    message.textContent = "Welcome to CIIT Training Institute";
}

Result

Welcome to CIIT Training Institute
Best practice: Prefer textContent for plain text. Avoid assigning untrusted user input to innerHTML, because interpreting it as HTML can introduce cross-site scripting risks.

4. Using innerHTML

The innerHTML property reads or replaces an element's HTML markup. Use it only when inserting trusted or safely sanitized HTML.

HTML

<div id="courseDetails"></div>

TypeScript

const courseDetails = document.getElementById("courseDetails");

if (courseDetails) {
    courseDetails.innerHTML =
        "<h3>TypeScript Course</h3>" +
        "<p>Learn TypeScript step by step.</p>";
}

Result

TypeScript Course

Learn TypeScript step by step.

Security tip: Do not insert untrusted form values or API content directly into innerHTML. Use textContent when you only need to show text.

5. Handling Button Click Events

Use addEventListener() to execute a function when an event occurs, such as a button click.

HTML

<button id="welcomeButton">
    Click Me
</button>

<p id="welcomeMessage"></p>

TypeScript

const welcomeButton =
    document.getElementById("welcomeButton");

const welcomeMessage =
    document.getElementById("welcomeMessage");

if (welcomeButton && welcomeMessage) {
    welcomeButton.addEventListener("click", () => {
        welcomeMessage.textContent =
            "Welcome to CIIT Training Institute!";
    });
}

Expected Behaviour

When the user clicks the button, the message appears below it.

Welcome to CIIT Training Institute!

How it works: The click event calls the registered function, and the function changes the paragraph's text.

6. Changing CSS Styles

You can update an element's inline styles through its style property. For larger design changes, CSS classes are usually easier to maintain.

HTML

<p id="status">Course Status: Pending</p>

TypeScript

const status = document.getElementById("status");

if (status) {
    status.style.color = "green";
    status.style.fontWeight = "bold";
    status.style.fontSize = "20px";
}

Result

Course Status: Pending

Alternative: Use classList.add(), classList.remove(), and classList.toggle() when you want to apply styles through CSS classes.

7. DOM Type Assertions

Methods such as getElementById() return a general HTML element type. When you need an input-specific property such as value, use an appropriate type assertion and check for a missing element.

HTML

<input id="studentName" type="text" />

TypeScript

const studentNameInput =
    document.getElementById("studentName") as HTMLInputElement | null;

if (studentNameInput) {
    studentNameInput.value = "Rahul";

    console.log(studentNameInput.value);
}

Expected Output

Rahul
Remember: A type assertion does not perform a runtime type check. Use it only when you know the selected element has the asserted type.

8. Reading User Input

The value property reads the current value of an input element. Form values are generally strings, so convert the value when a number is required.

HTML

<input id="studentAge" type="number" />

<button id="checkAgeButton">Check Age</button>

<p id="ageResult"></p>

TypeScript

const ageInput =
    document.getElementById("studentAge") as HTMLInputElement | null;

const checkAgeButton =
    document.getElementById("checkAgeButton");

const ageResult =
    document.getElementById("ageResult");

if (ageInput && checkAgeButton && ageResult) {
    checkAgeButton.addEventListener("click", () => {
        const age = Number(ageInput.value);

        if (ageInput.value.trim() === "" || !Number.isFinite(age)) {
            ageResult.textContent = "Please enter a valid age.";
        } else if (age < 18) {
            ageResult.textContent = "You must be at least 18.";
        } else {
            ageResult.textContent = "Age accepted.";
        }
    });
}

Validation Logic

Empty Input

Ask the user to enter an age.

Age Below 18

Display the minimum-age message.

Age 18 or Above

Display the accepted message.

9. Working with Multiple Elements

Use querySelectorAll() to select multiple matching elements. You can loop through the resulting collection to update their content.

HTML

<p class="course">Java</p>
<p class="course">Python</p>
<p class="course">.NET</p>

TypeScript

const courses = document.querySelectorAll(".course");

courses.forEach((course, index) => {
    console.log((index + 1) + ". " + course.textContent);
});

Expected Output

1. Java
2. Python
3. .NET

10. Working with CSS Classes

The classList property provides methods to add, remove, check, and toggle classes without directly rewriting the entire class attribute.

const courseCard = document.getElementById("courseCard");

if (courseCard) {
    courseCard.classList.add("active");
    console.log(courseCard.classList.contains("active"));

    courseCard.classList.remove("active");
    courseCard.classList.toggle("highlighted");
}

Common Methods

Method Purpose
add() Adds a CSS class.
remove() Removes a CSS class.
contains() Checks whether a class exists.
toggle() Adds the class when absent and removes it when present.

11. Common DOM Manipulation Mistakes

Element Not Found

Check for null before accessing an element's properties.

Wrong Element Type

Use appropriate DOM types such as HTMLInputElement for input elements.

Script Runs Too Early

Ensure the DOM is ready before selecting elements.

Unsafe innerHTML

Avoid inserting untrusted data as HTML. Use textContent when displaying plain text.

Input Is Always a String

Convert numeric input and validate it before using it in calculations.

Type Assertion Is Not Validation

Type assertions guide TypeScript's checker but do not verify the actual object at runtime.

Summary

  • The DOM represents an HTML document as a tree of objects.
  • Use getElementById() and querySelector() to select elements.
  • Use textContent for safe plain-text updates.
  • Use innerHTML carefully when HTML markup is required.
  • Use addEventListener() to handle user interactions.
  • Use appropriate DOM types when accessing input-specific properties.
  • Use querySelectorAll() to work with multiple elements.
  • Use classList to manage CSS classes.