Replacing jQuery

jQuery is great. If you’re making AJAX calls, manipulating the DOM, or creating a dynamic web page, jQuery can simplify your code and make the whole creation process faster.

However, jQuery isn’t always needed, and in fact – dare I say – it’s a little over-used. In this post, I’ll show a few ways that you can replace some of the commonly used functions of jQuery with a few lines of pure JavaScript.

For an example of a site that doesn’t require the might of jQuery, look no further than this very site. There isn’t much DOM manipulation going on and no AJAX calls to be seen, but a few helper functions were required to simulate some of the nice bits of jQuery.

Now, you may well ask: what’s this guy got against jQuery, it’s awesome! Why would I want to purposefully avoid it? To which I’d reply: A 90kb (2,500 line) script on a small website could be considered overkill. Use it where it makes sense, and when it doesn’t, I hope the below make help you fight the cravings.

Now, with the justifications out of the way, let’s get into it. For each scenario I’m showing the jQuery code, then the pure JavaScript code, and in most cases the helper function required to support the latter.

 

Selecting Elements

In jQuery, I can select, a div with something like:

$('#my-div')...

This is an easy one. The pure JavaScript version will look like this:

getEl('my-div')...

All I need is a function like so.

function getEl(id){
	return window.document.getElementById(id);
}

In my opinion, ‘getEl’ is about as short as you can go without getting abstract.

 

Creating Elements

In jQuery it’s fairly easy to create a new element, you simply say:

$('#my-div').append('<p>Hello World!</p>');

The pure JavaScript equivalent is a little longer:

getEl('my-div').appendChild(makeEl('p', 'Hello World!'));

The supporting function creates an element of the type I pass as the first parameter. If I pass a second parameter it will add this as a text node within the new element.

function makeEl(type, text) {
	var resultEl = document.createElement(type);
	if (text) { resultEl.appendChild(document.createTextNode(text)); }
	return resultEl;
}

In a recent project where jQuery was out of the question, but I needed to do some fairly heavy DOM manipulation, the above function was extended to allow the definition of attributes and styles as well:

function makeEl(type, text, attrs, styles) {
	var newEl = document.createElement(type);
	var prop;
	if (text) { newEl.appendChild(document.createTextNode(text)); }
	for (prop in attrs) {
		if (newEl[prop] !== undefined) {
			newEl[prop] = attrs[prop];
		} else {
			console.log(prop + ' is not a vaild attribute.');
		}
	}
	for (prop in styles) {
		if (newEl.style[prop] !== undefined) {
			newEl.style[prop] = styles[prop];
		} else {
			console.log(prop + ' is not a vaild style.');
		}
	}
	return newEl;
}

Of course in production you might want to drop the console.log() lines. This allows me to create an element including attributes and styles in one line, e.g.:

makeEl('div',
	'my div!',
	{id: 'my-new-div', className: 'shiny'},
	{backgroundColor: '#eee', border: '1px solid #222'}
	);

OK, so that’s four lines, and admittedly a little messy. Normally for me this level of complexity would signal that it’s time bring in jQuery. Its .append() method is really very clever. It will parse everything in the brackets and intelligently do things like create ids, classes and styles and even nested elements.

 

Emptying an Element

If you are manipulating the DOM, and you want to, for example, empty a list and repopulate it with a new list, it’s dead simple in jQuery:

$('#my-div').empty();

Without jQuery, the same can be accomplished like so:

emptyEl('my-div');

With a little help from a function:

function emptyEl(id) {
	while (getEl(id).firstChild) {
		getEl(id).removeChild(getEl(id).firstChild);
	}
}

 

Adding Events

This is one of the areas where jQuery really excels – particularly if you’re creating some complex events on many elements. But it ain’t rocket science.

In jQuery:

$('#my-div').on('click', function() {
	//Do Something...
});

The equivalent in pure JavaScript:

addEvent('my-div', 'click', function() {
	//Do Something...
}

And this is the little helper function:

function addEvent(id, event, func) {
	if (getEl(id).addEventListener) {
		getEl(id).addEventListener(event, func, false);
	}
	if (getEl(id).attachEvent) { //older IEs
		getEl(id).attachEvent(event, func, false);
	}
}

 

AJAX

This is very simple in jQuery. The example here is specifically fetching JSON:

$.getJSON('myFile.php', function(data){
	//Do Something with 'data'...
});

But things aren’t so bad in pure JavaScript:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
	if (xhr.readyState !== 4 || xhr.status !== 200) { return; }
	//Do Something with xhr.responseText...
};
xhr.open('GET', 'myFile.php', true);
xhr.send();

If I’ve got a site with many AJAX calls and/or want to support JSON in older browsers I’ll either use jQuery or at least load in JSON2.js.

 

Wrapping Up

As you can see above, working without the support of jQuery doesn’t need to be avoided at all costs. jQuery should be seen as a great helper, not a necessity.

And lastly, for a chuckle.

7 thoughts on “Replacing jQuery

  1. Mark V.

    Avoiding jQuery is a good idea, I fully support it. Bonus points: jQuery-less projects repel inferior programmers; there are just too many “jQuery developers” out there, who cannot grasp simple concepts of JavaScript language. Usually this leads to inefficient code, if not downright broken.

    Reply
  2. navaneeth

    Hi, nice post! :)
    I follow some of these. It would be great if you add jQuery alternatives of removing events (.off), count of event handlers ($._data(ele, ‘events’).length), etc!
    thanks! :)

    Reply
    1. David Gilbertson Post author

      Thanks. This is more difficult. Mozilla has a nice polyfill for enabling .removeEventListener here.

      But personally, if I’m adding and removing event listeners, I would use jQuery, or something like backbone if it’s an MVC project.

      Reply
  3. Jacob Nelson

    Cool.
    You haven’t covered most of the raw javascript functionalities which is equivalent to jQuery.

    I completely agree with Mark V.

    I happened to work with certain (inferior) programmers, who always talks about jQuery, but they never agree that jQuery is a Javascript library. Most pathetic case is that, they don’t even know the difference between Javascript and jQuery.

    Here is two good blog posts, which have more comparisons. This might be useful for others too.

    http://toddmotto.com/is-it-time-to-drop-jquery-essentials-to-learning-javascript-from-a-jquery-background/

    http://www.leebrimelow.com/native-methods-jquery/

    Reply
  4. Dustin Deus

    JQuery serves as library to help you modify the DOM in an elegant and simple way. Of course, JQuery is not a necessity but it will be a necessity if you want to keep your code consistent when you play a lot with the DOM. In addition jquery consists of lots of cross-browser inconsistencies which your equivalent code doesn´t contain apart from the fact that your article don´t speak about JQuery but about DOM manipulation librarys in general. As you say “A 90kb (2,500 line)” In my opinion the use case for which this library is to big is very strange perhaps for very little..little project but this is not practical.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>