Skip to content

Instantly share code, notes, and snippets.

@franklinjavier
Created February 4, 2015 13:59
Show Gist options
  • Select an option

  • Save franklinjavier/85b950b6b099bef0bd15 to your computer and use it in GitHub Desktop.

Select an option

Save franklinjavier/85b950b6b099bef0bd15 to your computer and use it in GitHub Desktop.
Workaround to querySelectorAll() and forEach
<ul>
<li data-tab="bla1">asdf</li>
<li data-tab="bla2">sadfaf</li>
<li data-tab="bla3">asdfa</li>
</ul>
// document.querySelectorAll returns a NodeList.
// First thing first, as opposed to other NodeList, this one is not live, mostly because the
// implementation of a live object would be terribly complicated for some selectors
// NodeList are a DOM interface introduced in DOM core level 1 (random guess)
// The ECMAScript binding (http://www.w3.org/TR/DOM-Level-3-Core/ecma-script-binding.html) defines
// NodeList as objects. Unfortunately, the spec is not very accurate in how this object should be
// implemented. It does not say if things are inherited or not, no word on NodeList.prototype
// The de-facto standard is apparently that the protoype chain looks roughly like:
// myNodeList -> NodeList.prototype -> Object.prototype
// As you can notice, Array.prototype is not here. It has to be noted that at the time NodeList were
// invented + standardized was before/at the time of ECMAScript 3.
// At this time, Array.prototype only had:
// .concat, .join, .pop, .push, .reverse, .shift, .slice, .sort, .splice, .unshift
// Most of these methods are not applicable to NodeList since they either write on the NodeList.
// .forEach, .filter, etc. came later on with ECMAScript 5 but it was too late to consider adding
// Array.prototype on the prototype chain (is it really too late?)
NodeList.prototype.forEach = Array.prototype.forEach;
HTMLCollection.prototype.forEach = Array.prototype.forEach; // Because of https://bugzilla.mozilla.org/show_bug.cgi?id=14869
document.querySelectorAll('li').forEach(function(el) {
console.log(el.getAttribute('data-tab'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment