Iterating over an HTMLCollection

I have always expressed my lack of interest in jQuery. I don’t like it as a framework, but I like even less the fact that it contributed to the creation of a wave of bloated websites. There are countless of sites that load jQuery just to do a transition, or to hide an object.

jQuery also contributed to the proliferation of plugins that don’t really do anything other than providing eye candy, but don’t improve the overall usability of a site, sometimes they even worsen it. jQuery also created a culture of instantaneous code, where people think everything is as easy as doing $().

Despite all its faults, jQuery did great things. It hid away the complexities of dealing with the DOM, it helped many people enter the world of Javascript, and it demonstrated that there are better ways to do things.

One of the things I like about jQuery is the fact that you can almost effortlessly apply changes to a collection of elements. Think for example, that you had to move all elements that had a certain class name to the left by 10px. Now, lets say you must do it with javascript. With jQuery you would do something like:


$('.className').css('left', '10px');

Compare that to the amount of code you have to use to do the same thing with vanilla js:


var nodes = document.querySelectorAll('.className');
for (var i = 0; nodes[i]; i++) {
  nodes[i].style.left = "10px";
}

That is not too bad, but it is not as simple as the online jQuery code. The for loop is just boilerplate code. There is a better way to do it:


function iterateCollection (collection) {
  return function(f) {
    for(var i = 0; collection[i]; i++) {
      f(collection[i], i);
    }
  }
}

This is a nice little function that will allow you to iterate over a collection of nodes, or an array even, and then it will call a function passing it the current index, and the element at that index. To call it, you simple do this:


iterateCollection(nodes)(function(node, i) {
  node.style.left = "10px";
});

While it may not be as little as the jQuery code, it eliminates the need for the library. Also, the function can be used with other functions to create more interesting patters.

I am currently working on a DOM library that takes advantage of this kind of patter as an implementation of functional programming for DOM manipulation.