Skip to content

Instantly share code, notes, and snippets.

@juanbrujo
Last active August 29, 2015 14:22
Show Gist options
  • Save juanbrujo/b6dc5bcf0a2445d21262 to your computer and use it in GitHub Desktop.
Save juanbrujo/b6dc5bcf0a2445d21262 to your computer and use it in GitHub Desktop.
Vanilla JavaScript useful variables (almost jQuery)

#Vanilla JavaScript useful variables (almost jQuery)

Tests: JSBin

Test 1: 1 element (ID)

$('#hola').style.color = 'red';

Test 2: 2 elements (selector)

$$('p').forEach(function(elems){
  elems.style.color = 'blue';
});

Test 3: 2 elements (classes)

$$('.paragraph').forEach(function(elems){
  elems.style.fontWeight = 'bold';
});

Test 4: 1 element (ID), bind 'click' event

$('#hola').on('click',function(ev){
  this.style.color = 'green';
});

Test 5: 2 elements (classes), bind 'click' event

$$('.paragraph').on('click',function(ev){
  this.style.color = 'yellow';
});

Thnx to bling.js & other repos.

/**
* returns first queried element
* use: $('#element')
*/
var $ = document.querySelector.bind(document);
/**
* returns array of targeted elements
* use: $('.elements')
*/
var $$ = document.querySelectorAll.bind(document);
/**
* Add 'on' event binding
* use: $('element').on('click', function(e){
* // your job
* });
*/
Node.prototype.on = window.on = function (name, fn) {
this.addEventListener(name, fn);
};
NodeList.prototype.__proto__ = Array.prototype;
NodeList.prototype.on = NodeList.prototype.addEventListener = function (name, fn) {
this.forEach(function (elem, i) {
elem.on(name, fn)
});
};
// Final notes: IE8+ support.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment