It's looping twice, because the first time you call to .css it loops through each element to add the first style, and then it loops through again on the second .css to add the second style. You could roughly replicate it with:
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.