Working with the DOM
The DOM is the page tree in the browser.
DOM means Document Object Model.
querySelector often returns Element | null.
Think of it as looking for a toy in a box that might be empty.
Null from querySelector
Always handle null.
Null means nothing was found.
Non-null assertions (!) are tempting but crash if the selector is wrong.
A selector is the search string for an element.
Generic querySelector
Pass an element type parameter so TypeScript knows the exact kind.
Like HTMLInputElement or HTMLButtonElement.
Do that after you have confirmed the element exists.
Or combine the generic with a null check.
Events and currentTarget
Event handlers receive typed events.
An event is a signal like a click or a key press.
Use currentTarget when you attached the listener to a known element type.
currentTarget is the element that owns the listener.
Creating elements
document.createElement returns a specific HTML element type.
The tag name tells TypeScript which kind.
That gives you the right properties right away.
Narrow element kinds
Sometimes you have a plain Element.
Check with instanceof before using special fields.
instanceof asks if the value was made as that kind.
Treat DOM lookups as maybe missing. Then narrow to the exact element type.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.