How to find a object in a NodeList in JavaScript

As web developers, there are plenty of situations where we want to traverse the DOM and find specific elements.

So, how exactly do we find an object in NodeList in JavaScript? Well, let’s say we query the DOM for all instances of a paragraph.

const nodes = document.querySelectorAll('p');

We now have a NodeList with a whole host of objects.

Since a NodeList is not actually an Array, how we traverse through it is not initially obvious. However, we can accomplish this with relative ease after converting the NodeList to an array and using some manipulation methods.

The latest ES6 way:

const foundParagraph = Array.from(nodes).find((node) => node === nodeRefToFind);

// note: nodeRefToFind must be the exact object you are looking for

We convert our paragraph NodeList into an Array using Array.from. And use .find() to match the desired item.

Alternatively, we can get the index of the desired item in the Nodelist:

const index = [].indexOf.call(nodes, nodes[nodeRefToFind]);
// 2

And with the index we can retrieve from the NodeList:

nodes[index]
Proudly published with Gatsby