Skip to content

Instantly share code, notes, and snippets.

@davilera

davilera/00-readme.md

Last active Nov 14, 2017
Embed
What would you like to do?
Vanilla JavaScript VS libraries

Some examples of the things one can do with Vanilla JavaScript. Comparison of Vanilla JS to jQuery and Underscore.js.

// jQuery
var element = $( '#element' );
var links = $( '.some-class' );
var articles = $( 'article' );
// Vanilla JavaScript
var element = document.getElementById( 'element' );
var links = document.getElementsByClassName( 'some-class' );
var articles = document.getElementsByTagName( 'article' );
// Element
var element = document.querySelector( '#element' );
// Array of elements
var links = document.querySelectorAll( '.some-class' );
var articles = document.querySelectorAll( 'article' );
// jQuery
var firstElement = jQuery( '#list li:first' );
var nextElement = firstElement.next();
// Vanilla JavaScript
var firstElement = document.getElementById( 'list' ).getElementsByTagName( 'li' )[0];
var nextElement = firstElement.nextElementSibling;
// jQuery
var element = $( '#element');
var scale = element.data( 'scale' );
element.data( 'scale', scale + 10 );
element.addClass( 'some-class' );
// Vanilla JavaScript
var element = document.getElementById( 'element' );
var scale = element.getAttribute( 'data-scale' );
element.setAttribute( 'data-scale', scale + 10 );
var classAttr = element.getAttribute( 'class' );
element.setAttribute( 'class', classAttr + ' some-class' );
$( '#post a' ).addClass( 'post-link' );
var links = document.getElementById( 'post' ).getElementsByTagName( 'a' );
for ( i = 0; i < links.length; ++i ) {
links[ i ].className += ' post-link';
}
// Underscore.js
_.each( list, iteratee );
var newList = _.map( list, iteratee );
var value = _.reduce( list, iteratee, memo );
var bool = _.every( list, predicate );
var bool = _.some( list, predicate );
...
// Vanilla JavaScript
list.forEach( iteratee );
var newList = list.map( iteratee );
var value = list.reduce( iteratee, memo );
var bool = list.every( predicate );
var bool = list.some( predicate );
...
document
.querySelectorAll( '#post a' )
.forEach( a => a.className += ' post-link' );
// Underscore.js
_.keys( object );
_.size( object );
_.values( object );
...
// Vanilla JavaScript
Object.keys( object );
Object.keys( object ).length;
Object.keys( object ).map( key => object[ key ] );
...
// Underscore.js
var result = _.pluck( list, 'attribute' );
// Vanilla JavaScript
var result = list.map( e => e.attribute );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment