Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

My .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? e.g

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

like image 558
Iladarsda Avatar asked Oct 13 '11 11:10

Iladarsda


People also ask

How do you create an array loop in jQuery?

Description of the syntax:The “each ()” method is used for iterating the array object in the loop format. The “jquery array” is represented to display array values or array objects inside of each () method. The “jquery callback function” represents the array index and array value inside of each () method.

Can we use forEach in jQuery?

each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.

How can you use array with jQuery?

Syntax And Declaration: var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"]; Type of Array: The type of an array is “object“. Iteration Approach: We use the length property of the array to iterate in the array. Iteration Approach using JQuery: jQuery provides a generic .


1 Answers

You could do:

var arr = $( 'a.cur:not(.apply)', '.profile-nav' ).map( function () {
    return $( this ).prop( 'class' ).split( ' ' )[0];
}).get();
like image 57
Šime Vidas Avatar answered Oct 14 '22 05:10

Šime Vidas