var i, elements = document.getElementsByClassName('widget');
for (i = 0; i < elements.length; i++) {
elements[i].style.color = "green";
}
for (i = 0; i < elements.length; i++) {
elements[i].style.fontSize = "16px";
}
Two loops. The "improved" suggestion would be roughly equivalent to: var i, elements = document.getElementsByClassName('widget');
for (i = 0; i < elements.length; i++) {
elements[i].style.color = "green";
elements[i].style.fontSize = "16px";
}
This is one loop, but it's still O(n). If there are 100 ".widget" elements on the page, the first code does 200 writes to the style property. The second code does 200 writes to the style property. The difference in jumps and compares isn't worth thinking about when style changes are so expensive, the difference is probably immeasurable.The second version is better just because it's cleaner code, but that's it.
In $(".widget").css("color", "green").css("font-size", "16px"); does the color of all the widgets change, and then the fontSize, or does the color/fontSize change together for each widget? I suspect the latter...
There is no extra DOM lookups, but there will certainly be two loops.
[0] https://github.com/jquery/jquery/blob/master/src/css.js#L102
[1] https://github.com/jquery/jquery/blob/master/src/css.js#L103
[2] https://github.com/jquery/jquery/blob/master/src/core.js#L75...
[3] https://github.com/jquery/jquery/blob/master/src/core.js#L75...
http://sherlockcode.com/demos/jquery/#!/src/css.js:102
Ctrl+Click on the jQuery.access call on the next line to jump to its definition.