Loop through Elements, Arrays and Objects using jQuery .each() Function

It is very important that you have a clean and manageable code at the client side and jQuery provides some very interesting functions and properties, which will allow you limit the size of your code and yet keep it functional and manageable. In this post, I am going to show you how you can loop through DOM elements, arrays and objects using jQuery .each() function.

jQuery .each() Function Example

The jQuery .each() function is an alternative to JavaScript for loop. The .each() function is not only efficient, but has many interesting properties, using which, you can easily and quickly iterate through elements, objects, arrays and simultaneously fetch and manipulate data, properties etc.

See this demo

However, there is a difference between two very similar jQuery each methods, those are, $('selector').each() and $.each(). The former ($('selector').each()) iterates through matched elements using a selector. The selector, in this context can be any DOM element (such as <div> or <span>) or a CSS Class defined to an element. And the later ($.each()) loops or iterates through jQuery objects or arrays. We’ll see both the functions in action here.

jQuery .each() Function

Here I have four <span> elements on my web page and each has a character in it. I wish to loop through each <span>, extract the characters and append it to a <p>. It sounds like a lengthy process. However, the .each() will make it simple.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body> 
    <span>A</span>
        <span>R</span>
            <span>U</span>
                <span>N</span>
    <p></p>
</body>
<script>
    $(document).ready(function () {
        // LOOP THROUGH EACH SPAN ELEMENT.
        $('span').each(function () {
            $('p').append(($(this).text()));
        });
    });
</script>
</html>
Try it

Output

A R U N
ARUN 

The <span> would show four different characters. However, the <p> now shows a single word.

Using jQuery .each() with .reverse() and .get()

We can use .each() with other jQuery functions to achieve some interesting results. I’ll use the same markup as above and read each character reverse.

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    
    <span>A</span>
        <span>R</span>
            <span>U</span>
                <span>N</span>
    <p></p>
</body>

<script>
    $(document).ready(function () {
        // LOOP AND SHOW SPAN VALUES, REVERSE.
        $($('span').get().reverse()).each(function () {
            $('p').append($(this).text());
        });
    });
</script>
Try it

Output

A R U N
NURA    <-- ALL CHARACTERS REVERSED.

jQuery .each() using Class as Selector

You can use a class name as selector to loop through elements. For example, I’ll create and add class to the <span> elements and pick values from spans that has a class property defined.

<style>
    .c1 { color: #000; }
    .c2 { color: #F00; }
</style>

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <p>Read values from elements that has a class defined!</p>

    <span class="c1">A</span>
        <span>R</span>
            <span>U</span>
                <span class="c1">N</span>
    <p></p>
</body>
<script>
    $(document).ready(function () {
        // GET VALUES OF SPANS WITH A SPECIFIC CLASS NAME.
        $('.c1').each(function () {
            $(this).addClass('c2');
            $('p').append($(this).text());
        });
    });
</script>
Try it

Output

A R U N
AN

I have assigned a CSS class to the first and last <span> in the above example. Therefore, using the class as selector (.c1), it picks only the first and last span values and does the necessary manipulations on the two only.

jQuery .each() Function with Parameters

You can pass parameters to the .each() function.

// .each() HAS PARAMETERS.
$('span').each(function (index, element) {
    console.log(element.className + ' ' + element.tagName + ' ' + element.innerHTML);
});

The index has an integer value that returns the index value of the elements, starting with the value 0. The parameter element (sometimes referred as just e) returns the elements properties. In the above example, it displays the class name that is attached to the <span>, the type of element (the <span>) and content in each element.

Using jQuery .each() with Arrays

Now, this example is slightly different from the examples above. I previously used a selector with .each() function that would loop through each matching (specified) element on the page. However, now I’ll use $.each() function to iterate through an array and retrieve the values in it.

<script>
    $(document).ready(function () {
        var arr = ['I', 'live', 'in', 'India'];
        $.each(arr, function (index, value) {
            $('p').css('fontSize', '25px');
            $('p').append(value + ' ');
        });
    });
</script>

The array in the above example has four static values. The $.each() iterates over each item in the array and appends the values to the <p>.

Output

I Live in India

The index sometimes plays an important role in locating a value in the array or an object. You can filter values to limit the result, based on the indexes. For example,

$.each(arr, function (index, value) {
    if (index == 3) {
        $('p').css('fontSize', '25px');
        $('p').append('Index: ' + index + ' has Value: ' + value);
    }
});

The output of this code will be India as I have set a condition using the index, which returns a value in the array whose index is 3.


Using jQuery .each() with Object

The $.each() function can work with objects too. Unlike arrays, if you are using an object as collection, the .each() function would return a key-value pair of the object.

<script>
    $(document).ready(function () {
        var obj = {
            'Name' : 'Arun Banik',
            'Blog': 'encodedna.com'
        };
        $.each(obj, function (key, value) {
            $('p').append(key + ': ' + value + '<br />');
        });
    });
</script>
Conclusion

There’s so much you can do with .each(). Use it in your app to understand the usefulness of this function. We have seen two variants of jQuery .each(), that is, $.each() and $(‘selector’).each() and both play an important role in an application. Not to mention, it reduces the length of your code drastically.

See this demo

Thanks for reading.

Previous - Create a Facebook like Notifications Window using jQuery and CSSNext - Add Rows to a Table Dynamically using jQuery



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner

Related Posts: