---
title: "TypeError: Object has no method 'forEach' in JavaScript"
description: "Iterating a NodeList in JavaScript using forEach - understanding why you get this error and how to fix it. Practical notes."
url: "https://h3manth.com/scribe/typeerror-object-has-no-method-foreach-in-javascript/"
canonical_url: "https://h3manth.com/scribe/typeerror-object-has-no-method-foreach-in-javascript/"
markdown_url: "https://h3manth.com/scribe/blog/typeerror-object-has-no-method-foreach-in-javascript.md"
publishDate: "2012-05-18T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["javascript","nodejs"]
word_count: 246
reading_time_minutes: 2
x_markdown_tokens: 528
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# TypeError: Object has no method 'forEach' in JavaScript

> Iterating a NodeList in JavaScript using forEach - understanding why you get this error and how to fix it. Practical notes.

Iterating a NodeList in JavaScript using forEach due to temptation, you have definitely come across **TypeError: Object has no method 'forEach'**

Before digging into the error, let's try to understand what a NodeList is!

**IDL Definition of NodeList is as below:**

```javascript
interface NodeList {
  Node item(in unsigned long index);
  readonly attribute unsigned long length;
};
```

> The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.

NodeList or collection of nodes are normally returned by methods like: `getElementsByTagName`, `getElementsByTagNameNS`, `Node.childNodes`, `querySelectorAll`, `getElementsByClassName` etc.

It's important to note that the items in a NodeList are accessible via an integral index, starting from 0.

So one would generally write a normal loop like below to access the elements of a NodeList, but when we try to apply a `forEach()` on it, we will get an error because it has no method by that name!

```javascript
for (var i = 0; i < nodeList.length; i++) {
  // do something with nodeList[i]
}
```

Simple trick to iterate NodeList is to use Array's `forEach()` on NodeList, like below:

```javascript
var forEach = Array.prototype.forEach;
var hrefs = document.querySelectorAll('a');
forEach.call(hrefs, function(link) { 
  console.log(link.src);
});
```

If that is more, how about the below ;)

```javascript
[].forEach.call(document.querySelectorAll('a'), function(elem) { 
  console.log(elem.src);
});
```

**Converting NodeList to Array:**

```javascript
myList = Array.prototype.slice.call(myNodeList);
```

Do let me know your tricks of doing the same! Happy Hacking!
