How to create an array from .each loop with jQuery

How can I create an array from the ".each" loop and use it outside 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 to create an array from all var = ClassesToApply ?

And how can I do something with this array? eg

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

+8
javascript jquery
source share
4 answers

If you declare a variable outside each , it will be available inside 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 significantly reduce your code.

+21
source share
 fxnReqValidation = function () { var InputTagArray = new Array; InputTagArray = document.getElementsByTagName("input"); for (var iCnt = 1; iCnt <= InputTagArray.length; iCnt++) { if ((g_Json[InputTagArray[iCnt].name].required == true) && (InputTagArray[iCnt].value == "")) { $("#errormsg").text("please enter all required fields"); } return false; } } 
+13
source share

You can do:

 var arr = $( 'a.cur:not(.apply)', '.profile-nav' ).map( function () { return $( this ).prop( 'class' ).split( ' ' )[0]; }).get(); 
+6
source share
 var list = $(".profile-nav ul li a.cur:not(.apply)"); list.each(function(){ // do your thing! }); 
0
source share

All Articles