Writing jQuery each() in Pure JavaScript

Published on February 21, 2019

The jQuery $.each() method can be replicated in vanilla JavaScript using natively available methods.

As an example consider the following list :

<ul class="team-standings">
    <li>Red Bull Racing</li>
    <li>Haas Ferrari</li>

If we were to use $.each to iterate over the elements, the jQuery code would be :

$('.team-standings li').each(function(index) {
    // current element


The same can achieved in JavaScript using a forEach loop and native selector functions :

  1. document.querySelectorAll : This method returns an array of elements that matches the CSS selector that is specified.
  2. document.querySelector : This method returns the first element that matches the CSS selector that is specified. Unlike document.querySelectorAll which returns an array, this returns only a single result.

Writing the same jQuery code in vanilla Javascript :

var li = document.querySelectorAll('.team-standings li');
li.forEach(function(element, index) {
    // current DOM element


Instead of $.this in jQuery, you can get the current DOM element through the first parameter of the forEach callback function.

In this Tutorial