Table of contents

M4Q Loops

M4Q's each() function is used to loop through each element of the target M4Q object.

About

The m4q object is an object that contains one or more DOM elements, and exposes all m4q functions. It’s very useful for multi-element DOM manipulation, looping arbitrary arrays, and object properties. In addition to this function, m4q provides a helper function with the same name that can be called without having previously selected or created DOM elements. M4Q's each() function is used to loop through each element of the target m4q object.


                    $.each($(...), function(...){

                    })
                

                    $(...).each(function(...){

                    })
                

Context

Context for iteration function is a element. For access to the context you can use this.


                    var array = ['one', 'two', 'three'];
                    $.each(array, function(){
                        console.log(this);
                    });
                    // Outputs: one two three
                

Arguments

Iteration functions receive arguments. For array like object or plain object, function receive element index and element. For json, function receive element key, element and element index.

Array like

                    var array = ['one', 'two', 'three'];
                    $.each(array, function(i, v){
                        console.log(i+">"+v);
                    });
                    // Outputs: 0>one 1>two 2>three
                
JSON

                    var json = {
                        name: "Vasya",
                        email: vasya@domain.com,
                        tel: "123456789"
                    };
                    $.each(element, function(k, v, i){
                        console.log(i+">"+k+">"+v);
                    });
                    // Outputs: 0>name>vasya 1>email>vasya@domain.com 2>tel>123456789
                

Set helper

If you already selects elements with m4q constructor, you can use helper m4q function each() to iterate by elements.


                    <ul>
                        <li>Item 1</li>
                        <li>Item 2</li>
                        <li>Item 3</li>
                    </ul>
                

                    $("li").each(function(i, el){
                        console.log(this); // HTMLElement li
                        console.log(i, el); // index 0, 1, 2, HTMLElement li
                    });