Forum Moderators: open

Message Too Old, No Replies

Selecting jQuery elements inside a loop

improving speed by using Javascript variables

         

csdude55

7:23 am on May 19, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I read this on a page referring to speeding up jQuery performance; it may have been linked in an earlier thread, I don't quite recall:

// as for loops, this is a big no-no
console.time('no cache');
for (var i=0; i<1000; i++) {
$('#list').append (i);
}
console.timeEnd('no cache');

// much better this way
console.time('cache');
var item = $('#list');

for (var i=0; i<1000; i++) {
item.append (i);
}
console.timeEnd('cache');


[code.tutsplus.com...]

But the loop I have includes a dynamic jQuery element; eg, $('#item_' + i):

function blahblah(x) {
for (var i=0; i < arr; i++) {
if (i == x) {
$('#item_' + i).css('color', '#E36627');
$('#foo_' + i).removeClass('mnOff', 'mnBottom').addClass('mnOn');
}

else {
$('#item_' + i).css('color', '#393939');
$('#foo_' + i).removeClass('mnOn');
}
}
}


I'm not sure how to create a dynamic Javascript variable outside of the loop, though. Do you guys think that this important enough to worry about? If so, any suggestions on how to do it?

jbnz

7:36 am on May 19, 2018 (gmt 0)

10+ Year Member Top Contributors Of The Month



To mimic the second piece of code in the first example could you use the jquery selector

[api.jquery.com ]

such that

var item = $('#list');


reads

var items = $("[id^='item_']");
var foos = $("[id^='foo_']");


for your purposes given your ids? Then iterate thru the two vars to do your css and class changes?

Someone with a better understanding of jquery will hopefully chip in soon.

(Edited my code - suddenly realised it was wrong!)

NickMNS

12:58 pm on May 19, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



But the loop I have includes a dynamic jQuery element; eg, $('#item_' + i):

I'm not sure what you are trying to achieve exactly. But a cleaner way of doing this (shown in plainJS) is:
Start by giving your #item_i elements a single class name eg: .items then,

var itemElems = document.getElementsByClassName("items");
itemElems.forEach(function(elem) {
// do stuff
});


I'm also not sure what's up with your #foo_i selector. I assume that it is child of item_i, in which case it could be selected as such. Now I am assuming that your are always selecting the same group of elements at the same time, as opposed to selecting a random subset that changes. This wont work for the later case.