Different ways to iterate a NodeList and search for a specific element

In Javascript, document.querySelectorAll( 'selector' ) searches all the elements in the document that match the CSS selector specified.

The issue would be that querySelectorAll returns a NodeList which is a collection of Nodes but it's not truly an Array, because of that we are unable to use methods that we find in the Array object.

The methods in a NodeList are:

  • NodeList.item()
  • NodeList.entries()
  • NodeList.forEach()
  • NodeList.keys()
  • NodeList.values()

As you can see some of them are iterators but we'll need some extra steps in order to retrieve a specific item from that NodeList.

Imagine that we have a collection of anchor tags and we want to find an element for a specific url

const allInputs = document.querySelectorAll( 'a' );  
const urlToSearch = 'https://github.com/byverdu';  
let found;  
let position;  
// Using forEach
allInputs.forEach(( link, index ) => {  
  // We'll need to know the position where the elements is placed
  if (link.href.indexOf( urlToSearch ) !== -1 ) {
    position = index;
  }
});
found = allInputs[ position ];  
// Using a for loop
for ( let i = 0; i <= allInputs.length; i++ ) {  
  // We'll need to know the position where the elements is placed
  if (allInputs[ i ].href.indexOf( urlToSearch ) !== -1 ) {
    position = index;
  }
}
found = allInputs[ position ];  
// Kind of a hack
found = [].find.call( allInputs, link => link.href === urlToSearch );  
// Only will work if using es6
found = Array.from( allInputs ).find( link => link.href === urlToSearch );

// We could do it in this way too
found = Array.from(  
  document.querySelectorAll( 'a' )
  ).find(
    link => link.href === urlToSearch
  );

Docs for NodeList

comments powered by Disqus