Joris Kluivers

I like to build software.

Vanilla Javascript

Updated Jan 16th 2013: Added vanilla looping using forEach.

All too often new web projects are started by immediately including a framework like jQuery into the page. This is not out of necessity but more out of convenience over having to write against the javascript DOM API’s. Even a lot of popular javascript tutorials now use jQuery by default resulting in an entire new generation of web developers not knowing about standard javascript API’s.

While jQuery and the likes offer a convenient (but in my opinion ugly) shorthand syntax and shield you away from browser incompatibilities they also add overhead. The minified jQuery library is 32kb and even the simplest functionality will add always be slower than native javascript alternatives. You’ll especially notice this on mobile devices which all have limited memory capacity.

Most modern browsers now all include new HTML5 DOM features that make life easier. Next time ask yourself why you’re actually using a framework, vanilla javascript might all you need.

As a way underappreciated technology I’m glad someone finally decided to give plain old javascript it’s own (humorous) framework page. Checkout the Vanilla js framework.

Listed below are a few nice vanilla js features you might not have used before.

Manipulating element classes

Add / remove / toggle classes
1
2
3
4
5
6
7
// fictional example to animate a notice in to/out of view
var notice = document.getElementById("#notice");
notice.classList.add("modal-visible"); // show
notice.classList.remove("modal-visible"); // hide

// or toggle
notice.classList.toggle("modal-visible");

Query using css selectors

1
2
3
4
5
6
// querySelector finds the first matching element
document.querySelector("#objectid");
document.querySelector("#objectid .someclass");

// querySelectorAll returns a list of all matching elements
document.querySelectorAll("#container li");

Shorthand

When you’re really attached to your jQuery / Prototype dollar shorthand, it’s easy to recreate it yourself using a simple function.

1
2
3
4
var $ = function(query) {
  return document.querySelector(query);
};
// Example: $("#container")

Loop over arrays using forEach

Javascript array’s have a nice function called forEach to apply a function to each of it’s elements.

1
array.forEach(callback[, thisArg]);

However this only works for arrays. DOM query functions like querySelectorAll usually return a node list. These lists act like arrays but really aren’t. And most importantly they don’t have the function forEach. To work around this and use forEach on everything that acts like a collection use the call function passing in the array and callback as arguments.

1
2
3
[].forEach.call(arrayOrNodeList, function(obj) {
  // do something with obj
});