Iladarsda Iladarsda - 5 months ago 24
jQuery Question

How to create an array from .each loop with jQuery

How can I create an array from inside of the '.each loop' and use it outside of the loop?


.each loop

// Loop through all but button with class .apply
$('.profile-nav ul li a').not('.apply').each( function() {

// if currently loop through element has .cur class
if( $(this).hasClass('cur') ) {

//Get the first class of the match element
var ClassesToApply = $(this).prop('class').split(' ')[0];

//How can I create an array from all ClassesToApply?

//var arr = jQuery.makeArray(ClassesToApply);
// This will create an array, but with one element only


How can I create an array from all
var = ClassesToApply

And than how can I do something with this array?

$( allClasses from an array as a selectors).doStuff();


If you declare a variable outside of the each, it will be accessible inside the each:

var yourArray = [];
$('.profile-nav ul li a').not('.apply').each(function() {
    if($(this).hasClass('cur')) {
        yourArray.push($(this).prop('class').split(' ')[0]);
//Here, yourArray will contain the strings you require.

Although as others have shown, there are ways to shorten your code significantly.