Fear of the DOM: why web developers use jQuery

Fear of the DOM: why web developers use jQuery

Many web developers use the jQuery library simply because they don't know the DOM.

I've started using JavaScript libraries with Prototype. Prototype is more than a simple tool: it's a multipurpose framework that can be used in many different contexts, not only for OOP. The problem (the only problem I mean) with Prototype is that its core design is targeted to experienced web developers with a strong background in JavaScript and programming. As stated above, Prototype is a framework, not a simple library. For that reason, Prototype assumes that you have a good experience with the DOM. That's why Prototype was superseded by jQuery. jQuery is more like a smart swiss knife designed to cover the underlying DOM routines. It's true that jQuery boosts up your productivity but it's also true that its design has created a generation of web developers with a really poor knowledge of the DOM.

Web developers fear the DOM because they simply ignore some basic concepts of its core design:

  1. The DOM is an API, not a programming language.
  2. The DOM is implemented in JavaScript.
  3. Browsers use a different engine for the DOM.
  4. O stands for "object". This means that HTML elements are treated as objects.
  5. Each object can have properties and methods.
  6. Each object can be extended, though this is not a recommended practice:
    
    HTMLElement.prototype.addClass = function(name) {
    	var element = this,
    		cls = element.className;
    		if(cls == '') {
    			element.className = name;
    		} else {
    			element.className = cls + ' ' + name;
    		}
    };
    
    
  7. DOM collections are "live". This means that every update is reflected in the document structure.
  8. When it comes to performance, DOM methods work much faster than jQuery methods because they're implemented in the browser's native language. The only exception is when we have to build large document structures. In this case we can use the nonstandard innerHTML property:
    
    var limit = 10000,
    	target = document.getElementById('test'),
    	i,
    	content = [];
    
    for(i = 0; i < limit; ++i) {
    	var part = '<p>' + (i + 1) + '</p>';
    	content.push(part);
    }
    
    target.innerHTML = content.join('');
    
    
  9. Today's DOM offers the querySelector() and querySelectorAll() methods to select elements using CSS selectors:
    
    var items = document.querySelectorAll('#nav li'),
    	len = items.length,
    	i;
    
    for(i = 0; i < len; i++) {
    	var item = items[i];
    	// do something with each list item
    }
    
    

The DOM is at the core of the jQuery library. Ignoring or not studying the DOM specifications is a wrong way to approach the JavaScript standard. Sooner or later you'll have to face the DOM whether you want it or not.