What is the reason behind the absence of forEach method on NodeListOf?

Here is the code that I wrote:

    var checkboxes = this.element.querySelectorAll("input[type=checkbox]") as NodeListOf<HTMLInputElement>;
    checkboxes.forEach(ele => {
        var key = ele.name;
        if (data.hasOwnProperty(key)) {
            if (!this.isArray(data[key])) {
                var temp = data[key];
                data[key] = [temp];
            }
        } else {
            data[key] = [];
        }
    });

Unfortunately, an error occurred:

Error TS2339: Property 'forEach' does not exist on type 'NodeListOf'.

interface NodeListOf<TNode extends Node> extends NodeList {
    length: number;
    item(index: number): TNode;
    [index: number]: TNode;
}

interface NodeList {
    entries(): IterableIterator<[number, Node]>;
    forEach(callbackfn: (value: Node, index: number, listObj: NodeList) => void, thisArg?: any): void;
    keys(): IterableIterator<number>;
    values(): IterableIterator<Node>;
    [Symbol.iterator](): IterableIterator<Node>;
}

I am puzzled as to why the 'forEach' method is missing in the 'NodeListOf' interface, since it inherits from 'NodeList' which does have the 'forEach' method. Can anyone shed some light on this issue?

Answer №1

It is not guaranteed that forEach will be available for this data type - it could exist, but it may not (for example in PhantomJS or IE), so TypeScript prohibits its usage by default. To loop through the elements, you can consider using:

1) Array.from():

Array.from(checkboxes).forEach((el) => { /* perform action */});

2) for-in loop:

for (let i in checkboxes) {
  if (checkboxes.hasOwnProperty(i)) {
    console.log(checkboxes[i]);
  }
}

Answer №2

If you want to avoid TypeScript complaints about using nodelist.forEach, one option is to convert a NodeList to an array. However, this approach can result in adding unnecessary code. A more elegant solution is to instruct TypeScript to recognize the native syntax of nodelist.forEach by including the dom.iterable library in your tsconfig.json file. Below is an example snippet from my own tsconfig.json configuration:

{
  "compilerOptions": {
  "outDir": "./public/js/",
  "noImplicitAny": true,
  "module": "es6",
  "target": "es5",
  "allowJs": true,
  "moduleResolution": "node",
  "rootDir": "src",
  "lib": [
    "es6",
    "dom",
    "dom.iterable"
  ],
  "typeRoots": [
    "node_modules/@types"
  ],
  "removeComments": false
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "public",
    "**/*.spec.ts"
  ]
}

Remember that not all browsers natively support nodelist.forEach, so it may be necessary to polyfill it. You can find more information on how to polyfill NodeList.forEach at https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach

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

Tips for adjusting the cursor's location on your screen

Is there a way to restrict mouse access to certain areas on a webpage using JavaScript? I want to programmatically change the position of the cursor when it enters these restricted zones. Essentially, I am looking to create non-mouseable areas on the page. ...

npm replace: troubleshooting npm script for replacing text across numerous files

I am currently attempting to swap out keywords in multiple files across various folders using regular expressions for the path: ./dist/src/**/**/**/*.scss Here is the npm script I am using: "build:src:replace:icon": "replace 'foo' 'bar&apos ...

What is the process for implementing pagination in vue-tables-2 with a Laravel REST API?

I'm looking to implement pagination on Vue server-table using a Laravel endpoint. How can I achieve this? Below is my component setup: <template> <div> <v-server-table :columns="columns" url="/object/find" :options="option ...

Creating a custom "dashboard" to manage Fabric.js elements

This question revolves around a more general topic of Javascript rather than fabric.js. Currently, I am examining the "kitchensink" demo in Fabric.js. When you click on the "Object" tab and choose an item in the drawing area on the left, the control panel ...

What is the best way to check the API response status in NextJS13?

Currently, I am experimenting with different methods to handle API HTTP status in my NextJS-13 project but so far nothing has been successful. Note: TypeScript is being used in this project. Below is my code snippet with a static 200 API response and the ...

Creating an array of objects through checkbox validation in AngularJS

$scope.data = [{ 'id': '1', 'itemName': 'mousepad', 'price': '20' }, { 'id': '2', 'itemName': &apo ...

TypeScript and the Safety of Curried Functions

What is the safest way to type curried functions in typescript? Especially when working with the following example interface Prop { <T, K extends keyof T>(name: K, object: T): T[K]; <K>(name: K): <T>(object: T) => /* ?? */; ...

How to Efficiently Remove Array Elements by Index in Typescript

What is the best way to remove an item by its index using Typescript? For example: let myArray = ['apple', 'banana', 'cherry', 'date']; // How can I delete the item at index 2? ...

Troubleshooting: Angular add/edit form issue with retrieving data from a Span element within an ngFor loop

I am currently working on an add/edit screen that requires submitting a list, among other data. The user will need to check 2-3 checkboxes for this specific data, and the saved record will have multiple options mapped. Here is what the HTML looks like: &l ...

How can jQuery determine if multiple selectors are disabled and return true?

I am currently working on a form in which all fields are disabled except for the "textarea" field. The goal is to enable the "valid" button when the user types anything into the textarea while keeping all other inputs disabled. I initially attempted using ...

The value remains unchanged when using Renderer2.setProperty()

I am attempting to update the value using the rendered.setproperty() method, where the value is updating the second time on a listen event These are the values that I am sending for the first time as blank in some widget <ols-giftcard-payment-widget ...

Advancement of a grunt chore within a digital platform

After constructing an app with grunt, I am now in the process of developing a web interface using node and angular to interact with this app. One feature I have implemented is a button that triggers a grunt task using childProcess in NodeJS: child_process ...

If the cursor hovers over an image, the onmouseover function does not work properly

Currently, I am developing a PHP page to display data from a database in a tabular format. Each column in the table represents an 'ATC Station'. When active, additional data is displayed upon hovering over the cell. Everything was running smooth ...

The Angular JS routes are not properly loading the required file from the provided TemplateURL when receiving a response from Node

I am trying to retrieve data from a MySQL database using node (routes.js) and have the results injected into club.html, which is then dynamically updated in index.html using ng-view. However, it seems that the JSON response from node is displaying directly ...

Prohibit communication by any means

Let's take a look at the following function overloads: function f(key: undefined); function f(key: string | undefined, value: object | undefined); I want to allow calls with a single explicit undefined argument f(undefined), but require two argument ...

Error encountered when using Prisma Client in conjunction with Next Auth.js

I encountered an error while working on Next Authentication with the Google adapter. The specific error message is as follows: ✓ Compiled /api/auth/[...nextauth] in 371ms (70 modules) (node:9269) [DEP0040] DeprecationWarning: The `punycode` module is dep ...

Unhandled rejection error occurred when attempting to redirect to a different page in Next.js version 13, resulting in a NEXT_REDIRECT error

Currently, I'm attempting to validate whether a user is logged in and if not, redirect them to the login page. Here's the code snippet I am using: import { onAuthStateChanged } from 'firebase/auth' import { auth } from '../src/fir ...

What causes the occurrence of "undefined" after multiple iterations of my code?

I've encountered a curious issue with the code snippet below. Everything seems to be running smoothly except for one thing - after a few iterations, I start getting "undefined" as an output. You can test this for yourself by running the code multiple ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

Creating a dynamic multiline chart using data from a JSON file with D

Here is the JSON structure I am working with: [{ "city": "roma", "giornata": [{"hour": 0, "vscore": 2.691172504799798, "sscore": 37476.67912706408}, {"hour": 1, "vscore": 2.691172504799798, "sscore": 37476.67912706408}, {"hour": 2, "vscore": 2.691 ...