Using the jQuery each() function to loop through classname elements

Brett picture Brett · Mar 13, 2011 · Viewed 57.5k times · Source

I am trying to use jQuery to loop through a list of elements that have the same classname & extract their values.

I have this..

function calculate() {

    // Fix jQuery conflicts
    jQuery.noConflict();

    jQuery(document).ready(function(){    

        // Get all items with the calculate className
        var items = jQuery('.calculate');



    });    

}

I was reading up on the each() function though got confused how to use it properly in this instance.

Answer

Darin Dimitrov picture Darin Dimitrov · Mar 13, 2011
jQuery('.calculate').each(function() {
    var currentElement = $(this);

    var value = currentElement.val(); // if it is an input/select/textarea field
    // TODO: do something with the value
});

and if you wanted to get its index in the collection:

jQuery('.calculate').each(function(index, currentElement) {
    ...
});

Reference: .each() and .val() functions.