I have 6 divs with ID”#first, #second … #sixth.
If I wanted to execute functions on each of these divs, I would set up an array that holding each div name. If I wanted to apply a function, I set up a for loop that iterates through each element in the array and (for example) changes the background color to red:
function updateAllDivsInTheList() {
for(var i = 0; i < array.size; i++)
$("#"+array[i]).changeCssFunction();
}
}
Whenever I create a new div, I would add it to the array.
The issue is, if I have a large number of divs that need to get updated (say 1000 out of 1200 divs), it may be a pain/performance tank to have to sequentially iterate through every single element in the array. Is there some alternative, more efficient way or data structure, of updating multiple divs? Maybe with some other more efficient data structure besides array? Or is what I am doing the most efficient way?
You should be caching your jQuery objects so that your list of names becomes a list of jQuery objects. Iterating over an array of 1000 items is fast. Building 1000 new jQuery objects every time is slow.
You can also chain multiple ids together into a single selector and avoid the (external) loop; jQuery will (probably) still implement this internally as a loop.
Note that updating the DOM a thousand times is going to be slow, more so in some browsers than in others. You might consider rethinking your code so that you’re adding or removing a class from some parent object, allowing some new CSS selector to match all child elements with a single DOM update.