I've been pondering why, when a class name is added to querySelectorAll, the type no longer shows up as HTMLDivElement.
document.querySelectorAll('div').forEach(item => {
// item type is HTMLDivElement
});
document.querySelectorAll('div.className').forEach(item => {
// item type is Element not HTMLDivElement
});
As a result, changing the style triggers an error:
document.querySelectorAll('div').forEach(item => {
item.style.display = 'none';
});
document.querySelectorAll('div.className').forEach(item => {
item.style.display = 'none'; // TS2339: Property 'style' does not exist on type 'Element'.
});
I have come across several workarounds (listed below), but I'm curious as to why this step is even necessary.
// Cast all items in NodeList to HTMLDivElement type
document.querySelectorAll<HTMLDivElement>('div.className').forEach(item => {
item.style.display = 'none';
});
// Cast current item to HTMLDivElement type
document.querySelectorAll('div.className').forEach(item => {
(item as HTMLDivElement).style.display = 'none';
});
// Only change style.display if instanceof HTMLDivElement
document.querySelectorAll('div.className').forEach(item => {
if (item instanceof HTMLDivElement) item.style.display = 'none';
});