document.q('.tile').each(tile => { tile.on('click', () => tile.toggleClass('expanded')); });
Why does this exist?

There are many common actions that I need to perform to change HTML elements in JavaScript for many of my projects, and it was tedious to use the built in methods. Sure, there are already libraries that do similar things, like jQuery, but jQuery is large and bloated. q.js is only 11.6 KB when it's not minified, and its method for querying the DOM is consistently as fast as the built in querySelectorAll method. In many cases, it's actually faster.

Quick Queries

JavaScript now includes native methods for querying the DOM using CSS-style selectors. If you want to find every element in the document that has a class named "tile", you could write the following:

document.querySelectorAll('.tile')

But before this became a built-in feature in browsers, you had to use a third party library if you wanted to do this. Using jQuery, the same query would look like this:

$('.tile')

This may look nicer, but there's a performance cost to this short code.

jQuery's $ method is consistently slower than the native methods. But if the native methods are faster than the JavaScript libraries, why would you use q.js now?

Simple. q.js is actually faster than querySelectorAll. For a query like the one above, you could write it like this using q.js:

document.q('.tile')

And because it's just a query based on a class, q.js would use the getElementsByClassName method. This is a native method, and it's faster than just using querySelectorAll in this case. q.js consistently picks the fastest native method available for the query, so it's never slower than querySelectorAll, but in many scenarios, it's faster.

Easy Writing, Easy Reading

q.js also makes the code for modifying HTML elements both easier to write, and easier to read. Take a look at this snippet and guess what it does:

document.q('.placeholder').each(el => { el.append('Hello world'); });

This would find every .placeholder element in the document and add the text "Hello world" to the end of each of those elements.

q.js includes methods for modifying classes, attributes, children, and event listeners. Just like the q method, these methods use the best available native methods to ensure speed and reliability.

Further Reading

Documentation and the the library itself are available on GitHub.