Home Fun Games Blog CDCRIFD CDRD Utilities About Settings
Back to CerebralDatabank's Blog

You Probably Don't Need jQuery

You don't want an extra ~90KB of code slowing down your website's load time. This page offers a solution for some common jQuery methods.

The Element Selector

With jQuery:

$("div.myclass")

With JavaScript:

/*To return the first matching element*/
document.querySelector("div.myclass")

/*To return a NodeList of all matching elements*/
document.querySelectorAll("div.myclass")

SIDENOTE: If you are using jQuery just because of this selector function (bad you!), just replace your jQuery call with this JavaScript code:

function $(selector) {
  return document.querySelectorAll(selector);
}

AJAX (Asynchronous JavaScript and XML)

With jQuery:

$.getJSON("/url/to/json", function(data) { /*Handle result*/ });

With JavaScript:

var request = new XMLHttpRequest();

request.open("GET", "/url/to/json", true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    /*Handle result*/
    var data = JSON.parse(request.responseText);
  } else {
    /*The server messed up*/
  }
};

request.onerror = function() {
  /*Handle an error*/
};

request.send();

EDIT

A new website (http://youmightnotneedjquery.com/) has all of the replacements, so I have not included them here.