2 ms·
It's even better with modern JS: document.querySelectorAll(selector).forEach(function (elem) { value = somevalue; }); Which is more obvious in intent and
by TazeTSchnitzel 14y ago
It's even better with modern JS:
document.querySelectorAll(selector).forEach(function (elem) { value = somevalue; });
Which is more obvious in intent and more flexible.
Except this doesn't work, because that's not a real array, it's a stupid NodeList. :(
So you'd have to do:
Array.prototype.slice.call(document.querySelectorAll('thing'), 0).forEach(function (elem) { value = somevalue; });
ugh.
- Offler 14y agoEveryone should be shimming ES5 array methods so your good example could quite happily run on older browsers too.
- gildas 14y agoYou don't need to call the slice method: Array.prototype.forEach.call(document.querySelectorAll('thing'), function (elem) { value = somevalue; });
- TazeTSchnitzel 14y agoAnd I could use underscore, a much more general-purpose library than jQuery to help me here, only 4kb. So: _.each(document.querySelectorAll('thing'), function (elem) { value = somevalue; }); (But then I might as well just use jQuery, I guess)