Borislav Hadzhiev
Fri Apr 01 2022·3 min read
Photo by Caroline Attwood
To select elements by class name in TypeScript:
document.getElementsByClassName()
method.HTMLCollectionOf<HTMLElement>
.This is the index.html
file for the examples in this article.
<!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.
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.
HTMLElement
and not to worry about it.We could have also been more specific and used the HTMLDivElement
type.
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.
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.
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.
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.
// ✅ 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.
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
.