Home

SiteMap

jQuery - How to iterate/loop through arrays, objects and elements using .each()

jquery

← Prev Next →

Here in this post, I am going to show you how to loop through DOM elements, arrays and objects using jQuery .each() function, something similar to forEach loop.

jQuery .each() Function Example

The jQuery .each() function has many interesting properties that you can use to quickly iterate through array, objects and elememnts. At the same time using its properties to fetch and manipulate data, properties etc.

See this demo

There is a difference between the two each methods that jQuery offer.

1) $('selector').each(), it 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.

2) $.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, reverse.
        $($('span').get().reverse()).each(function () {
            $('p').append($(this).text());
        });
    });
</script>
Try it

Output

A R U N
NURA    <-- All characters reversed.

👉 You might also like this... How to reverse a string or a text in JavaScript using "while" loop

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 Next →

聚圣源起名八字打分免费测试五行属金取名起名秘密森林百度云给孩子起个名字姓景如何起笔名辛巴燕窝事件开店起名网站免费取名内裤店起名大全中草药起名字女孩宝宝起名常用字梦见起名字起名叫韩鸭血粉丝加盟中国反导系统蒲柳之质中美联合军演女装店铺起名半藏森林是什么梗个性语言属鼠 宝宝起名杨式宝宝起名济宁车管所女生用靖起名好吗给小老鼠起名张五常带辰字的公司起名河北辛集清水二手房我的2007不负众望淀粉肠小王子日销售额涨超10倍罗斯否认插足凯特王妃婚姻让美丽中国“从细节出发”清明节放假3天调休1天男孩疑遭霸凌 家长讨说法被踢出群国产伟哥去年销售近13亿网友建议重庆地铁不准乘客携带菜筐雅江山火三名扑火人员牺牲系谣言代拍被何赛飞拿着魔杖追着打月嫂回应掌掴婴儿是在赶虫子山西高速一大巴发生事故 已致13死高中生被打伤下体休学 邯郸通报李梦为奥运任务婉拒WNBA邀请19岁小伙救下5人后溺亡 多方发声王树国3次鞠躬告别西交大师生单亲妈妈陷入热恋 14岁儿子报警315晚会后胖东来又人满为患了倪萍分享减重40斤方法王楚钦登顶三项第一今日春分两大学生合买彩票中奖一人不认账张家界的山上“长”满了韩国人?周杰伦一审败诉网易房客欠租失踪 房东直发愁男子持台球杆殴打2名女店员被抓男子被猫抓伤后确诊“猫抓病”“重生之我在北大当嫡校长”槽头肉企业被曝光前生意红火男孩8年未见母亲被告知被遗忘恒大被罚41.75亿到底怎么缴网友洛杉矶偶遇贾玲杨倩无缘巴黎奥运张立群任西安交通大学校长黑马情侣提车了西双版纳热带植物园回应蜉蝣大爆发妈妈回应孩子在校撞护栏坠楼考生莫言也上北大硕士复试名单了韩国首次吊销离岗医生执照奥巴马现身唐宁街 黑色着装引猜测沈阳一轿车冲入人行道致3死2伤阿根廷将发行1万与2万面值的纸币外国人感慨凌晨的中国很安全男子被流浪猫绊倒 投喂者赔24万手机成瘾是影响睡眠质量重要因素春分“立蛋”成功率更高?胖东来员工每周单休无小长假“开封王婆”爆火:促成四五十对专家建议不必谈骨泥色变浙江一高校内汽车冲撞行人 多人受伤许家印被限制高消费

聚圣源 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化