Using document.getElementById
or document.querySelector
does not guarantee that you will find a matching element. This is why the return type in Typescript is specified as HTMLElement | null
.
By using type assertion like as HTMLElement
, you are stating that you always expect to have an HTMLElement
and not a null
value. Rather than just checking if an element exists, you are asserting its presence.
If your assertion turns out to be incorrect and you actually end up with null
instead of an
HTMLElement</code, it will result in a runtime error when trying to manipulate properties like <code>.innerHTML
on a
null
object.
The reason for not finding a matching element even though it appears to exist within your application cannot be determined from the information provided here.
However, I can assist you in handling the possibility of null
values in your Typescript code by providing an example snippet:
const show = document.getElementById('row');
if ( show ) {
// Inside this if statement block, 'show' will definitely be an `HTMLElement`
show.innerHTML = "new inner HTML";
} else {
console.error("No element was found with id 'row'");
}
<div class="container">
<div id="row"></div>
</div>