Sling Academy
Home/TypeScript/Working with Document.createElement() in TypeScript

Working with Document.createElement() in TypeScript

Last updated: February 14, 2024

Introduction

In this tutorial, we dive into the powerful capabilities of working with Document.createElement() within the TypeScript ecosystem. Understanding how to dynamically create and manipulate elements in the DOM is a fundamental skill for modern web development. TypeScript, a superset of JavaScript, enhances this process by adding type safety and other useful features, making our development experience more robust and error-free.

To kick things off, let’s cover what Document.createElement() actually does. This method creates an HTML element specified by tagName, such as 'p', 'div', or any valid HTML element. It’s incredibly useful for dynamically adding content to your web page.

However, TypeScript introduces a layer of type-checking that can initially seem to complicate things but, in reality, offers a more disciplined approach to manipulating the DOM. Let’s explore this with examples.

Getting Started

First, ensure TypeScript is installed in your project. If you haven’t done so, you can install TypeScript globally via npm:

npm install -g typescript

Next, initialize a new TypeScript project:

tsc --init

This command generates a tsconfig.json file where TypeScript compiler options are set. For our examples, ensure the "dom" library is included in your compiler options to have access to DOM typings:

{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "es6"
    ]
  }
}

This setup ensures our environment is ready for manipulating DOM elements with TypeScript.

Creating an Element

Let’s create a simple example where we make a new <div> and add it to the body of our HTML document:

const newDiv: HTMLElement = document.createElement('div');
newDiv.innerText = 'Hello, TypeScript and DOM!';
document.body.appendChild(newDiv);

Here, we explicitly declare newDiv as type HTMLElement. This is TypeScript enforcing its type-checking prowess, ensuring that we’re working with the correct type of object.

Adding Attributes

Enhancing elements with attributes (e.g., classes, ids) is straightforward:

newDiv.setAttribute('class', 'my-class');
newDiv.id = 'uniqueId';

These methods add a class and an ID to our <div>. TypeScript’s IntelliSense will help prevent typos and errors in attribute names, a common issue in plain JavaScript.

Event Listeners

Attaching event listeners to our dynamically created elements is also a breeze:

newDiv.addEventListener('click', (event: MouseEvent) => {
  alert('Div clicked!');
});

The type MouseEvent gives us all the properties associated with a mouse event, leveraging TypeScript’s type system to make our code more predictable and safer.

Adding Children

It’s often necessary to nest elements within our dynamically created elements. Here’s how:

const childElement: HTMLElement = document.createElement('span');
childElement.innerText = 'I'm a child element';
newDiv.appendChild(childElement);

As with the parent element, we make use of TypeScript’s type annotations to ensure that our childElement is indeed an HTMLElement. This practice greatly aids in maintaining a structured and error-free codebase.

TypeScript and Custom Elements

TypeScript shines when working with custom elements. Let’s define a custom element:

class MyCustomElement extends HTMLElement {
  constructor() {
    super();
    // Custom element setup here
  }
}

window.customElements.define('my-custom-element', MyCustomElement);

This code snippet creates a new custom element <my-custom-element>. With TypeScript, we gain the advantage of strongly typed classes and constructors, ensuring our custom elements are built with precision.

Tips for Efficiency

  • Use type assertions wisely: When you’re absolutely sure about an element’s type, type assertions can simplify your code, but use them sparingly and wisely.
  • Method chaining: Many DOM methods return the object they were called on, allowing for method chaining. This can make your TypeScript code more concise and readable.
  • Leverage TypeScript utilities: Utilize TypeScript’s utility types, like Partial<HTMLElement>, to work with objects that might only partially meet a certain type’s criteria.

In conclusion, Document.createElement() is a versatile method that, when combined with TypeScript, provides a powerful toolkit for dynamic web development. By applying the concepts and examples laid out in this tutorial, you’ll be well-equipped to create rich, interactive web applications with confidence.

Next Article: Using getElementByClassName() method in TypeScript

Previous Article: TypeScript: How to Get/Set the Hash Segment of a URL

Series: TypeScript: Intermediate & Advanced Tutorials

TypeScript

You May Also Like

  • TypeScript: setInterval() and clearInterval() methods (3 examples)
  • TypeScript sessionStorage: CRUD example
  • Using setTimeout() method with TypeScript (practical examples)
  • Working with window.navigator object in TypeScript
  • TypeScript: Scrolling to a specific location
  • How to resize the current window in TypeScript
  • TypeScript: Checking if an element is a descendant of another element
  • TypeScript: Get the first/last child node of an element
  • TypeScript window.getComputerStyle() method (with examples)
  • Using element.classList.toggle() method in TypeScript (with examples)
  • TypeScript element.classList.remove() method (with examples)
  • TypeScript: Adding Multiple Classes to An Element
  • element.insertAdjacentHTML() method in TypeScript
  • TypeScript – element.innerHTML and element.textContent
  • Using element.removeAttribute() method in TypeScript
  • Using getElementById() method in TypeScript
  • Using Window prompt() method with TypeScript
  • TypeScript – window.performance.measure() method (with examples)
  • Working with the window screen object in TypeScript