logo
post image

Writing jQuery each() in Pure JavaScript

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>Mercedes</li>
    <li>Ferrari</li>
    <li>Red Bull Racing</li>
    <li>Renault</li>
    <li>Haas Ferrari</li>
</ul>

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

$('.team-standings li').each(function(index) {
    // current element
    console.log($(this).text());

    console.log(index);
});

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
    console.log(element.textContent);

    console.log(index);
});

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