a terse dom selection api
It's a tiny little napkinfull of code that lets you omit jQuery without going insane. It's literally just document.querySelector / document.querySelectorAll but the latter returns an Array instead of a NodeList and both have an extra optional context
argument.
- Because
document.querySelectorAll
is too long to type - Because
NodeList
doesn't have forEach - Because I have become accustomed to terse code
Would you rather write this:
var divsNodeList = document.querySelectorAll('div');
var divsArray = Array.prototype.slice.call(divsNodeList);
divsArray.forEach(function(div) {
console.log(div.textContent);
});
or this?
$$('div').forEach(function(div) {
console.log(div.textContent);
});
Yes! In fact, you definitely want to use jQuery if you want compatibility with older browsers and/or all the million other cool things that jQuery provides. If all you want is to query the DOM and you're only needing browsers that support it natively, you shouldn't have to use jQuery just to get a humane API. That's where 2bux comes in.
0.291 kB
Using Bower:
bower install 2bux
(you can also just grab the code here)
Supports both AMD and browser globals using UMD.
The $
and $$
variables are placed in your global scope unless you are using AMD.
With AMD, to get both $
and $$
, you should do this:
var $ = require("2bux"), $$ = $.$$;
$(selector, context); // returns a single element
$$(selector, context); // returns an array of elements
selector
is a CSS selectorcontext
is an optional DOM element (defaultdocument
). Only children ofcontext
are queried. It's as if you had calledquerySelector
orquerySelectorAll
on that DOM element rather than on thedocument
object.
// get an element
var element = $('#special');
console.log(element.innerText);
// get an array of elements
var divs = $$('div');
console.log(divs.length);
// iterate over an array
$$('div').forEach(function(div) {
console.log(div.innerText);
});
// get children of an element
var parent = $('#foo');
var children = $$('.bar', parent);
npm install
to install dependenciesgrunt test
to testgrunt
to build