Borislav Hadzhiev
Fri Apr 01 2022·2 min read
Photo by Olivia Hutcherson
To use the document.getElementsByClassName()
method in TypeScript, use a
type assertion to type the collection of elements correctly, e.g.
const boxes = document.getElementsByClassName('box') as 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>; Array.from(boxes).forEach(box => { console.log(box.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', ) as HTMLCollectionOf<HTMLDivElement>; Array.from(boxes).forEach(box => { console.log(box.innerText); });
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 = Array.from( document.getElementsByClassName('box') as HTMLCollectionOf<HTMLElement>, ); boxes.forEach(box => { console.log(box.innerText); });
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 in 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>
.