Very simple alternative to jQuery

Often, in many small or very small projects, you include jQuery only to have a conviniend DOM-selectors access via $(selector) and except this, you don't use jQuery at all. In cases like that using neither jQuery nor smaller Zepto.js isn't pretty wise.

Here is an example on how to achieve same effect in pure JS with querySelector and querySelectorAll.

This example is an adapted and extended version of Mozilla Developer Network's QuerySelector Code Snippets article.

Add these two simple functions anywhere within your JavaScript code:

function $(selector, el)
{
    if (!el) el = document;

    return el.querySelector(selector);
}

function $$ (selector, el)
{
    if (!el) el = document;

    return Array.prototype.slice.call(el.querySelectorAll(selector));
}

And... you're done! :]

You can now access any property of a particular object, like this:

console.log($('#button').id);

Or you can traverse through collection (array) of objects. For example:

var divArr = $$('div');

for (var i = 0; i < divArr.length; i++) if (divArr[i].id !== '') console.log(divArr[i].id);

What about attaching events? Quite simple though:

$('#link').onclick = function()
{
    alert($('#link').href);

    return false;
}

This is, of course, very simple and limited set of examples. You can do whatever you want with this...

Leave a Reply