3 ms·
To make that work for all elements of that class, you could rewrite it as document.querySelectorAll('.myclass') .forEach(el => el.style.display = 'block'
by bijection 9y ago
To make that work for all elements of that class, you could rewrite it as
document.querySelectorAll('.myclass')
.forEach(el => el.style.display = 'block')
The jQuery is still shorter, but the vanilla js is definitely manageable.
- no_gravity 9y agoUnfortunately, querySelectorAll returns a NodeList, not an Array. So you cannot use forEach() on it.
- hawkice 9y agoNodeList also implements forEach: https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach https://developer.mozilla.org/en-US/docs/Web/API/NodeList/fo...
- collinmanderson 9y agoIt's a very recent addition. IE11 doesn't have it for sure.
- no_gravity 9y agoNot in Edge though.
- hawkice 9y agoThe page I linked has a compatibility chart that says Edge 16 has it (no idea if that's a planned release, haven't ever used Edge).
- darepublic 9y agoYou can use Array.prototype.forEach.call(nodelist, fn), or Arrays.from(nodelist).forEach
- panzi 9y agoI don't use Windows so I can't test it, but would this work as a polyfill? NodeList.prototype.forEach = Array.prototype.forEach; In Chrome this even returns true: NodeList.prototype.forEach === Array.prototype.forEach
- emergie 9y agoTested in IE11, document.documentMode===11 Array.prototype.forEach.call(document.querySelectorAll('div'), console.log) seams to work
- tracker1 9y agoArray.from(document.querySelectorAll('.myclass')) .forEach(el => el.style.display = 'block')
- collinmanderson 9y agoThough ie11 doesn't have Array.from()
- bonesss 9y agoHrmmm... maybe someone should make a library that would smooth over browser differences and provide a consistent element selection syntax? Call it JavascriptSelection, or jSelection?
- emergie 9y agoimho 'JavascriptQuery' or 'jQuery' sounds better, oh wait...
- tracker1 9y agoI tend to polyfill older browsers, Array.from is a pretty small one. Sad thing is at a point where it's probably worth it to have 2-3 builds in place... 1 for legacy browsers, one for modern without modules, and one for modules/import/http2 support. Just haven't taken the time... at least the main app I work on at work doesn't need to support IE11. Latest Edge,, Firefox, Safari and Chrome ... and Chrome is the primary target.