Have you ever wondered why querySelectorAll('div') gives back a list of HTMLDivElement elements, while querySelectorAll('div.className') provides a list of Element elements in TypeScript?

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';
});

Answer №1

Here is the definition you need:

https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts#L11347

(if the link changes in the future, here's a permalink to the current version: https://github.com/microsoft/TypeScript/blob/4a7b6dc7497db7847bfa01c2e747fb5e7c200224/lib/lib.dom.d.ts#L11347)

It looks like there are specific definitions for various HTML & SVG elements, providing a more tailored list for those instances. In this case, I would recommend using:

document.querySelectorAll<HTMLDivElement>('div.className')

for optimal results.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unhandled promise rejection - The function get is not part of this.categoryMap

I am facing an issue with calling functions of the Map (get, set, keys, etc) within my function. The map I am working with is returned from a firebase query. Here's a snippet of my code: categoryMap = new Map<Number, String>(); //called onInit ...

Error in React.tsx Material UI Tab - Avoid using curly braces "{}" as a data type

Currently, I am working on a React TS project and facing an issue while trying to import the Material UI tabs for scrollable functionality. The specific Tabs/Scrollable Tabs example from Material-UI documentation is what I'm referring to: https://mate ...

Typescript: object containing at least one property with the type T assigned

Is there a method to write the HasNumber interface in Typescript without receiving an error due to the fact that the HasNumberAndString interface includes a property that is not of type number? I am looking for a way to require the HasNumberAndString int ...

What is the method to determine the size of an array of objects where each object contains its own internal array?

Here is the data that I have: var a=[ { name: "time", Details:[ {value:"month",checked:true,id:1} ] }, { name: "product", Details:[ {value: ...

The most secure method for retrieving User Id in AngularFire2

I'm currently facing a dilemma in determining the most secure method to obtain an authenticated user's uid using AngularFire2. There seem to be two viable approaches available, but I am uncertain about which one offers the best security measures ...

In TypeScript, how can we specify that a key is mandatory for an object but it can be referred to by two different names?

Essentially, I'm faced with a situation where I need to handle a style object that must contain either the maxHeight or height properties. If one of these properties is included, the other becomes unnecessary. Despite my efforts, I have been unable to ...

The result should display the top 5 application names based on the count property found within the ImageDetails object

data = { "ImageDetails": [ { "application": "unknownApp, "count": 107757, }, { "application": "app6", "count": 1900, }, { & ...

Combining numerous interfaces into a unified interface in Typescript

I'm struggling to comprehend interfaces in Typescript, as I am facing difficulty in getting them to function according to my requirements. interface RequestData { [key: string]: number | string | File; } function makeRequest(data: RequestData) { ...

Issue with forkJoin in the share component (and merging boolean variables) is not defined

I am facing an issue with my service where I need to share the result of a forkjoin, but the component is showing up as undefined Here is my service logic layer: @Injectable({ providedIn: 'root' }) ...

After I subscribe, why do the variables of my object become undefined?

Just starting out with Angular and using Angular9. I attempted to subscribe to an observable in the following code: I have a service that makes an HTTP request and returns an Observable. The subscription appears to be working fine. ngOnInit() { this.in ...

The parameter type 'Object' cannot be assigned to the parameter type 'string'

Everything seems to be working fine in my application, but I am encountering the following error message: The argument of type 'Object' is causing an issue and cannot be assigned to a parameter of type 'string' Here is the code snip ...

Having trouble reloading a seekbar (input range) in Angular 7 with a function?

I am currently in the process of developing a music player using Angular 7, and below is the HTML code for my component: <div class="track-controller"> <small>{{musicPlayerService.getCurrentTime()}}</small> <div class="progress- ...

The EventEmitter in Angular 8 is prohibiting the emission of an Object

Is there a way I can emit an Object instead of primitive data types? I have an object const amount = { currenty: 'USD', total: '10.25' }; that I need to emit to the parent component. export class MyChildComponent implements OnInit { ...

In TypeScript, an interface property necessitates another property to be valid

In the scenario where foo is false, how can I designate keys: a, b, c, bar as having an undefined/null/optional type? Put simply, I require these properties to be classified as mandatory only when foo is true. interface ObjectType { foo: boolean; a: nu ...

In Typescript, it is not permitted to assign a variable as a value within a styled array

Encountering a peculiar issue with TypeScript, Emotion.css, and React. The following code functions without any issues: import styled from '@emotion/styled-base'; const Layout = styled('div')([ { height: 48, color: ...

What causes the typescript error in my code: The argument being passed is either a string, an array of FilterData, an array of numbers, or an array of Moments, which is not compatible with a parameter of type 'string'?

When writing my code, I have the need to utilize various types for different scenarios. Depending on the situation, the type may be a string, number[], FilterData[] (a custom type), or Moment[]. To address this requirement, I defined the type as: export ty ...

Angular 6 Material now allows for the selection of a mat-tab-link by displaying an underlining bar

My website features a mat-tab-nav-bar navigation bar, but I'm facing an issue with the mat-tab-link blue underlining bar. It doesn't move to highlight the active button, instead, it stays on the first button. However, the buttons do change into t ...

Exploring the latest upgrades in React 18 with a focus on TypeScript integration

I am currently working on a complex TypeScript project with React and recently made the decision to upgrade to the new version of React 18. After running the following commands: npm install react@18 npm install react-dom@18 npm install @types/react-dom@18 ...

Discovering ways to fetch an array of objects using object and arrays in JavaScript

When comparing an array of objects with a single object and listing the arrays in JavaScript, specific conditions need to be met to retrieve the array of objects: If the itemvalue and idvalue are the same, check if the arrobj cid has the same codevalue ...