Iteration in Native Javascript

Omar Barguti
2 min readApr 20, 2021

Like JQuery, native JavaScript supports querying the DOM using standard CSS selectors. This is typically done using the function ‘document.querySelectorAll()’. However, unlike the JQuery selector function, this function return a NodeList object as opposed to a JavaScript array. This can be challenging because the NodeList object does not support iteration. There are several tricks one can do to manipulate the NodeList object and iterate over its contents.

The ‘for’ Loop Approach
This approach relies of using a standard JavaScript For loop to iterate over the NodeList. Elements in the NodeList can be accessed using the standard ‘[]’ operator at a given index. The length of the iteration is determined by accessing the ‘.length’ property of the NodeList.

var nodeList = document.querySelectorAll("div.toolbar-icon");for(var i= 0, len = nodeList.length; I < len; ++i) {
nodeList[i].innerText= "Index "+ i;
};

The Array.prototype.slice Function
This approach relies on invoking the ‘slice’ function off the JavaScript’s Array prototype object. The ‘slice’ function assumes the zeroth index if no parameter is supplied. This will convert the NodeList to an array object that can be iterated over using the native ‘forEach’ function. It is important to invoke the built-in ‘call’ function that invokes the ‘slice’ function in the context on the NodeList.

var nodeList = document.querySelectorAll("div.toolbar-icon")
var elements = Array.prototype.slice.call(nodeList);
elements.forEach(function(e, i) {
e.innerText= "index: "+ i;
});

The [].forEach Function
This approach creates an empty array inline using the ‘[]’ notation, and then it invokes the ‘forEach’ function available natively on all JavaScript arrays. It is necessary to invoke the ‘call’ function to set the scope to the NodeList.

var nodeList = document.querySelectorAll("div.toolbar-icon");
[].forEach.call(nodeList, function(e, i) {
e.innerText= "Index: "+ i;
});

Creating You Own Helper Library
Since iterating over NodeLists becomes a common task when using native JavaScript, it is a good idea to wrap all the reusable logic into a custom function. This custom function can be moved into a common library of reusable prefills and functions that are used throughout the application.

// Creating the Custom Helper Function
function $(selector) { return [].slice.call(document.querySelectorAll(selector)); }
// Invoking the Custom Function
$("div.toolbar-icon").forEach(function(e, i) {
e.innerText= "Index: "+ i;
});

--

--

Omar Barguti

An enthusiastic architect and full-stack developer with many years working with enterprise software and cloud services in multiple domains.