Javascript Journey: document.querySelectorAll()

(Aside: I really should make a post about the first project that I’ve been working on… next time, haha)

So we’ve been journeying into Javascript for the past week-ish or so. We were interrupted by Thanksgiving break, but we’re back at it!

I’ve been implementing some fundamental methods that Javascript provides:

  • document.getElementById()
  • Element.addEventListener()
  • window.location.hash
  • Element.classList.remove()*
  • Element.classList.add()*
  • Element.querySelectorAll()

*classList.remove() and classList.add() is really handy sans jQuery, though it doesn’t have very good support on IE. Cest le vie…

What I want to chat about today is Element.querySelectorAll(). So apparently if you print out your selection console.log(Element.querySelectorAll()) you get what looks like an array. Great, seems straight forward enough.

But running Array.isArray(Element) on your element returns false. What? Well that explains why all solutions I’ve been looking up to traverse my ‘array’ has been coming up with some variation of the below to traverse the ‘array’:

<span class="token keyword">var</span> divs <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">querySelectorAll<span class="token punctuation">(</span></span><span class="token string">'a'</span><span class="token punctuation">)</span><span class="token punctuation">;<br></br></span>``<span class="token punctuation">  [</span><span class="token punctuation">]</span><span class="token punctuation">.</span>forEach<span class="token punctuation">.</span><span class="token function">call<span class="token punctuation">(divs</span></span><span class="token punctuation">,</span><span class="token keyword">function</span><span class="token punctuation">(</span>div<span class="token punctuation">)</span><span class="token punctuation">{<br></br></span><span class="token comment" spellcheck="true">    // do something</span><span class="token punctuation">;<br></br></span><span class="token punctuation">  }</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

Turns out that what document.querySelectorAll returns is actually a NodeList, and what [] ) is doing is creating an empty array, and using the array’s prototype method through Javascript’s .call() to allow the NodeList to take advantage for the the array’s .forEach() method.

This seems a bit messy, but I guess it’s the solution I have for now!

Until next time =)

Duncan Leung

Front End Developer at

Irvine, CA

Subscribe to Duncan Leung: Javascript and Front End Development

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!