Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of selectors: for loop vs. $.each

Tags:

jquery

Given the following array of selectors (each of which are display: none in the our css) and for loop:

var arr = ['#home', '#news', '#tidy'];

for (i=0;i<=arr.length;i++){
    $(arr[i]).toggle();
}

What is an equivalent using $.each ( and presumably $(this) )?

Edit

OK I understand using join:

var s = arr.join();
$(s).toggle();

I did not realize that "toggle like many other jQuery methods calls each method internally so there is no need to use each" so +1 to you @undefined, however...

The question was original put forth because even when I:

$.each(arr, function(){
    $(this).text("my id is " + this + ".");
});

I get undefined (!) errors. (OK to be fair there was .toggle and .insertAfter etc., I'm attempting to simplify) Why is the above not equivalent to:

$('#home').text('my id is #home.');
$('#news').text('my id is #news.');
$('#tidy').text('my id is #tidy.');

?

Edit 2

OK it was a syntax issue - $(this) requires a prepending '' +:

$('' + this).text('My id is ' + this + '.')

Is there a rule as to when $(this) requires such treatment?

like image 531
Ragamffn Avatar asked Dec 01 '25 06:12

Ragamffn


1 Answers

Try

var arr = ['#home', '#news', '#tidy'];
$(arr.join(',')).toggle();

$(arr.join(',')) => $('#home, #news, #tidy'), which selects all 3 elements then toggle() operates on all the selected elements.


If you do

$.each(arr, function(){
    $(this).text("my id is " + this + ".");
});

the this is actually a string object not a string primitive so what you get in return form $(this) is a jQuery object wrapping a string object not the element that the selector will match. Adding a string primitive '' to a string object gives you a string primitive which is why it works that way.
If you have to use $.each better to use the arguments passed to the callback function, the first argument is the index of the array and the second is the value at the index.

$.each(arr, function(index, value){
    $(value).text("my id is " + this + ".");
});

http://jsfiddle.net/2TPLD/

like image 68
Musa Avatar answered Dec 03 '25 19:12

Musa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!