Tag Archive for: selector

Short selectors like jQuery

Using JavaScript is some kind of annoying when you have to select DOM elements, in those cases we could miss jQuery because JavaScript is simply too long.

// Select one element
document.querySelector("#peter");
document.querySelector(".staff"); // get the first one
document.querySelector(".staff").querySelector("#age");
// Select all elements
document.querySelectorAll(".staff") // get an array

We don’t like to repeat things when we are coding, if you define the next code at the beginning of your JavaScript you will be avaliable to do it similar even better than jQuery.

function $(selector) {
    return document.querySelector(selector);
}

function $$(selector) {
    return document.querySelectorAll(selector);
}

Element.prototype.$ = function(selector) {
    return this.querySelector(selector);
};

Element.prototype.$$ = function(selector) {
    return this.querySelectorAll(selector);
};

Now you can write our example shorter.

// Select one element
$("#peter");
$(".staff"); // get the first one
$(".staff").$("#age");
// Select all elements
$$(".staff") // get an array

It’s easy to keep in mind because $ behaves like jQuery with CSS selectors and $$ does the same but it allows you to select multiple elements. The first one return the element and the second one an array of elements.

Just one more thing, you cannot use jQuery with this code because jQuery use $ too, if you need it you have to change the $ in our code for another thing, ie: qS.