Friday, October 2, 2015

Lose the jQuery Bloat ­— DOM Manipulation with NodeList.js

In recent years, jQuery has become the de-facto JavaScript library on the web. It irons out many cross-browser inconsistencies and adds a welcome layer of syntactic sugar to client-side scripting. One of the main pain points it abstracts away is DOM manipulation, but since its inception, native browser APIs have improved dramatically and the idea that You May Not Need jQuery has started to gain in popularity.

Here are some reasons why:

  1. jQuery includes a bunch of features that you don’t need or use (so the weight is unnecessary).
  2. jQuery is too many things to too many people. Often smaller libraries can accomplish certain tasks better.
  3. In terms of DOM manipulation, browser APIs can now do most of what jQuery can.
  4. Browsers APIs are more in sync now, e.g. using addEventListener instead of attatchEvent.

So What's the Problem?

[author_more]

The problem is that DOM manipulation using vanilla (or plain) JavaScript can be a pain compared to jQuery. This is because you have to read and write more redundant code, and deal with the browser’s useless NodeList.

First let’s look at what a NodeList is according to MDN:

NodeList objects are collections of nodes such as those returned by Node.childNodes and the document.querySelectorAll method.

And sometimes there are live NodeLists (which can be confusing):

In some cases, the NodeList is a live collection, which means that changes in the DOM are reflected in the collection. For example, Node.childNodes is live.

This can be a problem because you can’t tell which are live, and which are static. Unless you remove each of the nodes from the NodeList and then check if the NodeList is empty. If it is empty then you have yourself a live NodeList (which is just a bad idea).

Also the browser doesn’t provide any useful methods to manipulate these NodeList objects .

For example, unfortunately it isn’t possible to loop through the nodes with forEach:

var nodes = document.querySelectorAll('div');
nodes.forEach(function(node) {
  // do something
});
// Error: nodes.forEach is not a function

So you have to do:

var nodes = document.querySelectorAll('div');
for(var i = 0, l = nodes.length; i < l; i++) {
  var node = nodes[i];
  // do something
}

Or are even left with using a “hack”:

[].forEach.call(document.querySelectorAll('div'), function(node) {
    // do something
});

The browser’s native NodeList only has the one method: item. This returns a node from a NodeList by index. It is completely useless when we can access that node just like we would with an array (using array[index]):

var nodes = document.querySelectorAll('div');
nodes.item(0) === nodes[0]; // true

That’s where NodeList.js comes in — to make manipulating the DOM with the browser’s native APIs as easy as it is with jQuery, but for only 4k gzipped.

The Solution

I created NodeList.js because I’ve always used the native DOM APIs, but wanted to make them more terse, so as to remove lots of the redundancy when writing my code (e.g. for loops).

NodeList.js is a wrapper around the native DOM APIs which allows you to manipulate an array of nodes (AKA my NodeList) as if it were a single node. This gives you much more functionality than the browser’s native NodeList objects.

If this sounds good to you, go grab a copy of NodeList.js from the official GitHub repo and follow along with the rest of this tutorial.

Usage:

Selecting DOM nodes is simple:

$$(selector); // returns my NodeList

This method uses querySelectorAll(selector) under the hood.

But How Does It Stack up against jQuery?

Glad you asked. Let’s put vanilla JS, jQuery and NodeList.js head to head.

Let’s say we have three buttons:

<button></button>
<button></button>
<button></button>

Let’s change the text of each button to “Click Me”:

Vanilla JS:

var buttons = document.querySelectorAll('button'); // returns browser's useless NodeList
for(var i = 0, l = buttons.length; i < l; i++) {
  buttons[i].textContent = 'Click Me';
}

jQuery:

$('button').text('Click Me');

NodeList.js:

$$('button').textContent = 'Click Me';

Here we see that NodeList.js can effectively treat a NodeList as a single node. That is to say, we have reference to a NodeList and we just set its textContent property to “Click Me”. NodeList.js will then do this for each node in the NodeList. Neat, huh?

If we wanted method chaining (à la jQuery) we would do the following which returns a reference to the NodeList:

$$('button').set('textContent', 'Click Me');

Now let’s add a click event listener to each button:

Continue reading %Lose the jQuery Bloat ­— DOM Manipulation with NodeList.js%


by Edwin Reynoso via SitePoint

No comments:

Post a Comment