Select elements by Class name using TypeScript

avatar

Borislav Hadzhiev

Last updated: Apr 1, 2022

banner

Photo from Unsplash

Select elements by Class name using TypeScript #

To select elements by class name in TypeScript:

  1. Use the document.getElementsByClassName() method.
  2. Type the selected elements correctly, e.g. as HTMLCollectionOf<HTMLElement>.
  3. Optionally convert the array-like object to an array to access array-specific methods.

This is the index.html file for the examples in this article.

index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <script src="./src/index.ts"></script> </body> </html>

And here is the related TypeScript code.

src/index.ts
const boxes = document.getElementsByClassName( 'box', ) as HTMLCollectionOf<HTMLElement>; // ✅ Get first element with class if (boxes.length > 0) { const first = boxes[0]; console.log(first.innerText); // 👉️ "Box 1" } // ✅ Convert to array const arr = Array.from(boxes); // ✅ Iterate over array arr.forEach(box => { console.log(box.innerHTML); }); // --------------------------------------------------------- // ✅ Get first element with class using querySelector const first = document.querySelector('.box') as HTMLElement | null; if (first != null) { console.log(first.innerText); }

The document.getElementsByClassName method has a return type of HTMLCollectionOf<Element>.

The Element interface does not have many of the properties you might need to use, e.g. style or innerText, so we used a type assertion to type the collection of elements as HTMLCollectionOf<HTMLElement>.

Type assertions are used when we have information about the type of a value that TypeScript can't know about.

We effectively tell TypeScript that each element in the collection will be of type HTMLElement and not to worry about it.

We could have also been more specific and used the HTMLDivElement type.

src/index.ts
const boxes = document.getElementsByClassName( 'box', // 👇️ collection of DIV elements ) as HTMLCollectionOf<HTMLDivElement>; if (boxes.length > 0) { const first = boxes[0]; console.log(first.innerText); // 👉️ "Box 1" } const arr = Array.from(boxes); arr.forEach(box => { console.log(box.innerHTML); });

Now we typed the boxes variable as a collection of div elements.

The types are consistently named as HTML***Element. Once you start typing HTML.., your IDE should be able to help you with autocomplete.

Some commonly used types are: HTMLInputElement, HTMLButtonElement, HTMLAnchorElement, HTMLImageElement, HTMLTextAreaElement, HTMLSelectElement, etc.

Note that the document.getElementsByClassName method doesn't return an array, it returns an array-like object of all child elements which have the provided class name.

If you need to access array-specific methods on the collection, you have to convert it to an array first.

src/index.ts
const boxes = document.getElementsByClassName( 'box', ) as HTMLCollectionOf<HTMLElement>; if (boxes.length > 0) { const first = boxes[0]; console.log(first.innerText); // 👉️ "Box 1" } // 👇️ convert to array const arr = Array.from(boxes); // 👇️ access array-specific methods arr.forEach(box => { console.log(box.innerHTML); });

We used the Array.from method to convert the array-like object to an array, so we can use the forEach method to iterate over it.

The type of the box variable on each iteration is HTMLElement, because we used a type assertion with the getElementsByClassName method.

Note that if you have to access element-specific properties, like the value property on an input element, you'd have to type the collection as a collection of that specific element type, e.g. HTMLCollectionOf<HTMLInputElement>.

If you need to get the first element with a specific class, use the document.querySelector method.

src/index.ts
// ✅ Get first element with class using querySelector const first = document.querySelector('.box') as HTMLElement | null; if (first != null) { console.log(first.innerText); }

The querySelector method has a return type of Element | null. If no element with the provided selector exists in the DOM, the method returns a null value.

If we have to access any element-specific properties on the variable, we have to use a type assertion to type it correctly

We used a simple if statement as a type guard to make sure the input variable doesn't store a null value before accessing properties on it.

TypeScript knows that the first variable has a type of HTMLElement in the if block and allows us to directly access its innerText property.

If you have to access an element-specific property type the variable as the specific type.

src/index.ts
const firstInput = document.querySelector( '.message', ) as HTMLInputElement | null; if (firstInput != null) { console.log(firstInput.value); }

We selected the first element with the message class in the DOM. We need to access the value property on the element and the HTMLElement interface doesn't have a value property, so we typed the element as an HTMLInputElement.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.