Web APIs, such as the DOM API, are available in many languages, including TypeScript. They offer standardized methods for accessing web documents and their elements. This guide will introduce TypeScript elements and how to use them on your web pages.
What Is DOM?
The Document Object Model (DOM) is a language- and platform-independent programming interface designed for creating and interacting with web page elements. It gives each HTML and XML document a tree structure in which there are nodes and objects representing all the parts and elements of the document.
This design enables programmatic access and manipulation of web pages. Using DOM APIs, you can add, alter, and delete the document content, style, and structure. They can make a static HTML document dynamic and functional.
What Is An Element?
HTML elements are one of the HTML node types and are typically represented by tags. Each of them tells the web browser how to construct a specific part of the web page.
For instance, you can use a paragraph element (<p> tag) to wrap around some content, indicating that the browser should treat them as a paragraph of text.
TypeScript Elements And DOM Manipulation
There are two interfaces you should pay close attention to: Element and HTMLElement.
Element is the base class on which all objects in an HTML/XML document, such as HTMLElement and SVGElement, are built on. Meanwhile, the HTMLElement interface represents all HTML elements. Other element interfaces are built on it.
For example, the HTMLParagraphElement interface inherits properties from HTMLElement. It also provides additional properties for accessing and manipulating paragraph <p> elements beyond what HTMLElement has.
The Document interface acts as the entry point to the content of a web page, representing the whole page when it is loaded in the browser. In TypeScript, it is represented by the global variable document.
The getElementById() method of the Document interface returns an Element object whose ID matches the given string. As element IDs need to be unique, this method provides a reliable solution for accessing HTML elements in a document.
This is how it is defined in TypeScript:
getElementById(elementId: string): HTMLElement | null;
When you provide a string, getElementById() will return either a HTMLElement object or a null value. null is a possible returned value because there is no way TypeScript can be certain it can always find the element matching your description.
This is a simple HTML file:
<!DOCTYPE html> <html lang="en"> <head> <title>LearnShareIT: TypeScript Elements</title> </head> <body> <h1 id="welcome-heading">Welcome to LearnShareIT</h1> <script src="script.js"></script> </body> </html>
We can use the getElementById() method to select the h1 heading to which we have assigned an ID:
let heading = <HTMLHeadingElement>document.getElementById("welcome-heading");
We use the angle-bracket syntax (also known as type assertions) to tell TypeScript we are expecting an HTMLHeadingElement object. You can then access properties of this object, such as innerText, which returns the rendered text content of the heading:
let heading_text = heading.innerText; console.log("h1:", heading_text);
h1: Welcome to LearnShareIT
The createElement() method of the Document interface creates an HTML element whose type is specified by the parameter tagName.
Its TypeScript definition:
createElement(tagName: string, options?: ElementCreationOptions): HTMLElement;
This is how you can create a paragraph element:
let p = document.createElement("p"); p.textContent = "LearnshareIT is developed to help students learn and share their knowledge more effectively.";
This example creates a <p> tag and uses the textContent property to change the text content it represents. Keep in mind that we have only created an HTML element, and it hasn’t been displayed on the page yet. Your document still looks like this:
You will need to change the page’s structure and add this element to a node to make it appear.
This method finds the first HTML element matching a selector or a group of CSS selectors you provide. It returns an Element object when there is a match and null otherwise.
Document.querySelector() is typically used to find the first element matching a class. For example, you have two paragraphs in the HTML file:
<p class="center">Welcome to LearnShareIT.</p> <p class="content">LearnshareIT is developed to help students learn and share their knowledge more effectively.</p>
You can use this statement to find the first element with the class “center”:
let p = <HTMLParagraphElement>document.querySelector(".center"); console.log("Content of the centered paragraph:", p.innerText);
Content of the centered paragraph: Welcome to LearnShareIT.
The DOM API allows for complex selectors. They are a powerful tool when you need to use several rules to describe your elements. For example, this is how you can find the button that has the name attribute “login” and is located in a div element with the class “big”:
let button = <HTMLButtonElement>document.querySelector("div.big button[name='login']");
Instead of only the first element, you can use the querySelectorAll() method to find all elements that match your selector.
This method will return a NodeList object, which is a collection of Element objects querySelectorAll() has identified.
The “matches” object in this example contains all paragraph elements in the document. We can use its length property to find the number of nodes in it, which is also the number of paragraphs:
let matches = <NodeList>document.querySelectorAll("p"); console.log("Number of paragraphs:", matches.length);
Number of paragraphs: 2
The Node interface provides an abstract class for HTML nodes. The Element interface extends it, and the HTMLElement interface, in turn, extends Element. You will need to be familiar with it to change the structure of an HTML document.
One of its commonly used methods is Node.appendChild(). It adds a child node to a parent node.
You can now add the paragraph element above into the heading element with appendChild():
The resulting HTML document will become the following:
To better understand, you can learn more in the detailed article about TypeScript Elements
- Get the value of an input element using TypeScript
- Check if an element contains a class using typescript
- To create an HTML element using TypeScript
- Solutions For Adding Types To Events In React Using TypeScript
- Hide/Show an Element using TypeScript
- Object is possibly null (document.getElementById) in TypeScript
- Property ‘click’ does not exist on type ‘Element’ in TypeScript
- Set CSS styles on an Element using TypeScript
- How to use the querySelector() method in TypeScript
- Add a class to the Body element using TypeScript
- How to disable a Button in TypeScript
My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.
Name of the university: HUST