Access an Element in Type Script

In TypeScript, to access HTML elements, we use the Document Object Model (DOM). The DOM defines an HTML and XML programming interface that visualizes a document's structure as a tree of nodes. Each node in the tree represents document elements like paragraphs, buttons, divs, headings, etc.

The document object in TypeScript serves as the doorway to the DOM, allowing us to easily access and manipulate HTML elements. There are several ways to access elements:

  • Using the document.getElementById() method

  • Using the document.querySelector() method

  • Using the document.getElementsByClassName() method

  • Using the document.getElementsByTagName() method

In this tutorial, we will focus on the two most commonly used methods: document.getElementById() and document.querySelector().

Using getElementById() Method

The document.getElementById() method is the most common way to access HTML elements in TypeScript. This method takes the id of the element as a parameter and returns the element as an object.

Syntax

let element = <HTMLElement>document.getElementById("elementId");
// or using type assertion
let element = document.getElementById("elementId") as HTMLElement;

Example

In this example, we have an HTML div element with an id of "root." We use the document.getElementById() method to access this element and manipulate it with two functions that change the text content and background color.

<html>
   <body>
      <h2>Access an <i>Element</i> in TypeScript</h2>
      <button onclick="changeText()">Change Text</button>
      <button onclick="changeBG()">Change Background Color</button>
      <div id="root" style="padding: 10px; background: #f0ecb8">
         This is a Div element!
      </div>
      <script>
         var root = document.getElementById('root');
         
         function changeText() {
            if (root) {
               root.innerHTML = 'The text is changed!';
            }
         }
         
         function changeBG() {
            if (root) {
               root.style.background = '#b8f0e5';
            }
         }
      </script>
   </body>
</html>

Important: If the element with the specified id does not exist, the method will return null. Always check for this before manipulating the returned element to avoid runtime errors.

Using querySelector() Method

The querySelector() method provides more flexibility by allowing you to select elements using CSS selectors. It returns the first element that matches the specified selector.

Syntax

const element = document.querySelector('#myDiv') as HTMLElement;
const elementByClass = document.querySelector('.myClass') as HTMLElement;
const elementByTag = document.querySelector('div') as HTMLElement;

Example

This example demonstrates using querySelector() to access elements and create a real-time text display. As you type in the input field, the div element updates to show the same text.

<html>
   <body>
      <h2>Access an <i>Element</i> in TypeScript</h2>
      <h4>Enter your text:</h4>
      <input oninput="changeInput()" id="inputField" type="text" />
      <div id="root" style="padding: 10px; background: #d5ed9c">Type something above...</div>
      <script>
         var root = document.querySelector('#root');
         var inputField = document.querySelector('#inputField');
         
         function changeInput() {
            if (root && inputField) {
               root.innerHTML = inputField.value || 'Type something above...';
            }
         }
      </script>
   </body>
</html>

Comparison of Methods

Method Selector Type Return Value Flexibility
getElementById() ID only Single element or null Limited to IDs
querySelector() Any CSS selector First matching element or null High - supports all CSS selectors

TypeScript Type Safety

When working with TypeScript, you can use type assertions to ensure type safety:

// Type assertion methods
const element1 = document.getElementById('myId') as HTMLDivElement;
const element2 = <HTMLInputElement>document.querySelector('#myInput');

// More specific typing for better IntelliSense
const button = document.getElementById('myButton') as HTMLButtonElement;
const input = document.querySelector('#myInput') as HTMLInputElement;

Conclusion

Both getElementById() and querySelector() are essential methods for accessing HTML elements in TypeScript. Use getElementById() for simple ID-based selections and querySelector() when you need the flexibility of CSS selectors. Always include null checks to ensure robust error handling.

Updated on: 2026-03-15T23:19:00+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements