@mattiacorvaglia

VanillaJS vs JQuery

Document ready

VanillaJS
document.addEventListener('DOMContentLoaded', function () {
  alert('Document ready!');
});
JQuery
$(document).ready(function () {
  alert('Document ready!');
});

Retrieve DOM elements

VanillaJS
Get single element (first match)
document.getElementById('foo');
document.querySelector('.foo');
Get multiple elements (all matches)
document.getElementsByClassName('foo'); // Returns live HTMLCollection[]
document.getElementsByTagName('span'); // Returns live HTMLCollection[]
document.querySelectorAll('.foo'); // Returns static NodeList[]
JQuery
Get single element (first match)
$('#foo');
$('.foo').filter(':first');
$('a').filter(':first');
Get multiple elements (all matches)
$('.foo');
$('a');

Classes manipulation

VanillaJS
document.getElementById('myDiv').classList.add('foo');
document.getElementById('myDiv').classList.add('foo', 'bar');
document.getElementById('myDiv').classList.remove('foo');
document.getElementById('myDiv').classList.remove('foo', 'bar');
document.getElementById('myDiv').classList.toggle('foo');
document.getElementById('myDiv').classList.toggle('foo', i < 10);
document.getElementById('myDiv').classList.replace('foo', 'bar');
JQuery
$('#myDiv').addClass('foo');
$('#myDiv').addClass('foo bar');
$('#myDiv').removeClass('foo');
$('#myDiv').removeClass('foo bar');
$('#myDiv').toggleClass('foo');
$('#myDiv').toggleClass('foo', condition);

Setting click handler

VanillaJS
document.getElementById('foo').addEventListener('click', function (event) {
  alert(`Hello ${index}`);
  event.preventDefault();
});
JQuery
$('#foo').click(function (event) {
  alert('Hello world!');
  event.preventDefault();
});

Manipulate data attributes

VanillaJS
document.getElementById('myDiv').getAttribute('data-foo');
document.getElementById('myDiv').setAttribute('data-foo', 'Hello World!');
document.getElementById('myDiv').removeAttribute('data-foo');

document.getElementById('myDiv').dataset.fooBar = 'Hello World!'; // <div id="myDiv" data-foo-bar="Hello World!"></div>
document.getElementById('myDiv').dataset.fooBar; // Hello World!
JQuery
$('#myDiv').attr('data-foo'); // Get
$('#myDiv').data('foo'); // Get
$('#myDiv').attr('data-foo', 'Hello World!'); // Set
$('#myDiv').data('foo', 'Hello World!'); // Set (not visibile in DOM)

Create DOM element

VanillaJS
var newDiv = document.createElement('div');
console.log(newDiv.outerHTML);
JQuery
var newDiv = $('<div/>');
console.log(newDiv.html());

Append a child element in DOM

VanillaJS
document.getElementById('myDiv').appendChild(newDiv);
JQuery
$('#myDiv').append(newDiv);

Get parent element

VanillaJS
var parent = document.getElementById('myDiv').parentNode;
JQuery
var parent = $('#myDiv').parent();

Async HTTP Request

VanillaJS
XMLHttpRequest
const uri = 'https://example.com';

function AJAX() {
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState === XMLHttpRequest.DONE) {
      (this.status === 200) ? onSuccess(this) : onError(this);
    }
  }
  xhr.open('GET', uri);
  xhr.responseType = 'json';
  xhr.send();
}

function onSuccess(xhr) {
  console.log('HTTP Response Status Code', xhr.status);
  console.log('HTTP Response Status Text', xhr.statusText);
  console.log('HTTP Response Body', xhr.response);
}

function onError(xhr) {
  console.error('HTTP Response Status Code', xhr.status);
  console.error('HTTP Response Status Text', xhr.statusText);
}

AJAX();
Fetch
const uri = 'https://example.com';
const jsonData = { username: 'example' };
const params = {
  method: 'POST',
  mode: 'cors',
  cache: 'no-cache',
  credentials: 'same-origin',
  headers: { 'Content-Type': 'application/json' },
  referrerPolicy: 'no-referrer',
  body: JSON.stringify(jsonData)
};
fetch(uri, params)
  .then(response => response.json())
  .then(responseBody => console.log('HTTP Response Body', responseBody));
fetch(uri, params)
  .then(response => {
    if (!response.ok) { // HTTP Status Code != 2xx
      throw new Error('Server Error');
    }
    return response.json();
  })
  .then(data => console.log('HTTP Response Body', data))
  .catch((err) => console.error(err));
async function AJAX() {
  const response = await fetch(uri, params);
  if (!response.ok) { // HTTP Status Code != 2xx
    throw new Error('Server Error');
  }
  return response.json();
}

AJAX()
  .then(data => console.log('HTTP Response Body', data))
  .catch(err => console.error(err));
(async () => {
  const response = await fetch(uri, params);
  if (!response.ok) { // HTTP Status Code != 2xx
    console.error('Server Error');
  } else {
    const responseBody = await response.json();
    console.log('HTTP Response Body', responseBody);
  }
})();
async function AJAX() {
  const response = await fetch(uri, params);
  if (!response.ok) {
    throw new Error('Server Error');
  }
  return response.json();
}
function onSuccess(data) { console.log('HTTP Response Body', data); }
function onError(err) { console.error(err); }

AJAX().then(onSuccess).catch(onError);
function onDone(response) {
  console.log('HTTP Response Status Code', response.status);
  if (!response.ok) { throw new Error('Server Error'); }
  return response.json();
}

function onSuccess(data) {
  console.log('HTTP Response Body', data);
}

function onError(error) {
  console.error(error);
}

fetch(uri, params).then(onDone).then(onSuccess).catch(onError);
JQuery
$.ajax
const uri = 'https://example.com';
const jsonData = { foo: 'Hello world!' };
const params = {
  url: uri,
  method: 'POST',
  cache: false,
  crossDomain: true,
  dataType: 'json',
  contentType: 'application/json',
  headers: { 'Accept': 'application/json' },
  data: JSON.stringify(jsonData)
};
$.ajax(params)
  .done(data => console.log('Response OK', data) )
  .fail(err => console.error('Network error', err.statusText) )
  .always(() => console.log('Request completed') );
Multiple requests synchronization
var req1 = $.ajax(params).done(onDone).fail(onFail);
var req2 = $.ajax(params).done(onDone).fail(onFail);
$.when(req1, req2).then(() => console.log('Requests completed'));

function onDone(data, textStatus, jqXHR) {
  console.log('HTTP Response Body', data);
}

function onFail(jqXHR, textStatus, errorThrown) {
  console.error('HTTP Request Method', this.type);
  console.error('HTTP Request URL', this.url);
  console.error('HTTP Request Content-Type', this.contentType);
  console.error('HTTP Respose Status Code', jqXHR.status);
  console.error('HTTP Respose Status Text', jqXHR.statusText);
  console.error('HTTP Respose Content-Type', jqXHR.getResponseHeader('Content-Type'));
  console.error('HTTP Respose Body', jqXHR.responseJSON);
}