Vanilla Javascript Equivalent Commands to Jquery

Complete Cheatsheet for jquery to vanillaJS migration

by Luigi Nori Date: 29-08-2019 jquery vanilla es6


jQuery is still a useful and pragmatic library, but chances are increasingly that you’re not dependent on using it in your projects to accomplish basic tasks like selecting elements, styling them, animating them, and fetching data—things that jQuery was great at. With broad browser support of ES6 (over 96% at the time of writing), now is probably a good time to move away from jQuery.

We are in process to remove jQuery from our framework and found those tips googling for some of the patterns over and over again. To spare you the time, We’ve compiled this practical reference guide with some of the most common jQuery patterns and their equivalents in JavaScript. We’ll cover how to move over to vanilla JavaScript from these concepts and functions:

Selecting elements Events .css() Document ready Classes .ajax() Creating elements HTML & text

Selecting elements

Selecting one or several DOM elements to do something with is one of the most basic elements of jQuery. The equivalent to $() or jQuery() in JavaScript is querySelector() or querySelectorAll(), which, just like with jQuery, you can call with a CSS selector.

// jQuery, select all instances of .box
$(".box");

// Instead, select the first instance of .box
document.querySelector(".box");

// …or select all instances of .box  
document.querySelectorAll(".box");

Or if you want to select the the entire divs in the DOM

// jQuery
var divs = $('div')

// Vanilla
var divs = document.querySelectorAll('div')

If you want to create a new div

// jQuery
var newDiv = $('<div/>')

// Vanilla
var newDiv = document.createElement('div')

Running a function on all elements in a selection

querySelectorAll() returns, just like jQuery does, an array of elements that you can work with. But whereas you can run a function with jQuery on the entire selection simply by calling it on the jQuery object, you’ll have to loop over the array of elements with JavaScript:

// with jQuery
// Hide all instances of .box
$(".box").hide();

// Without jQuery
// Loop over the array of elements to hide all instances of .box
document.querySelectorAll(".box").forEach(box =>{ box.style.display = "none"}

Finding one element within another

A common jQuery pattern is to select an element within another element using .find(). You can achieve the same effect, scoping the selection to an element’s children, by calling querySelector or querySelectorAll on an element:

// With jQuery
// Select the first instance of .box within .container
var container = $(".container");
// Later...
container.find(".box");

// Without jQuery
// Select the first instance of .box within .container
var container = document.querySelector(".container");
// Later...
container.querySelector(".box");

Traversing the tree with parent(), next(), and prev()

If you wish to traverse the DOM to select a subling or a parent element relative to another element, you can access them through nextElementSibling, previousElementSibling and parentElement on that element:

// with jQuery
// Return the next, previous, and parent element of .box
$(".box").next();
$(".box").prev();
$(".box").parent();

// Without jQuery
// Return the next, previous, and parent element of .box
var box = document.querySelector(".box");
box.nextElementSibling;
box.previousElementSibling;
box.parentElement;

Attributes

How to retrieve/manipulate attributes in vanilla js

// jQuery
$('img').filter(':first').attr('alt', 'My image')

// Vanilla
document.querySelector('img').setAttribute('alt', 'My image')

Working with events

There’s a myriad of ways to listen to events in jQuery, but whether you’re using .on(), .bind(), .live or .click(), you’ll make do with the JavaScript equivalent .addEventListener:

// With jQuery
$(".button").click(function(e) { /* handle click event */ });
$(".button").mouseenter(function(e) {  /* handle click event */ });
$(document).keyup(function(e) {  /* handle key up event */  });

// Without jQuery
document.querySelector(".button").addEventListener("click", (e) =>{ /* ... */ });
document.querySelector(".button").addEventListener("mouseenter", (e) =>{ /* ... */ });
document.addEventListener("keyup", (e) =>{ /* ... */ });

Or if you want to listen the entire a href content in DOM

// jQuery
$('a').click(function() {
  // code…
})

// Vanilla
[].forEach.call(document.querySelectorAll('a'), function(el) {
  el.addEventListener('click', function() {
    // code…
  })
})

Event listening for dynamically added elements

jQuery’s .on() method enables you to work with “live” event handlers, where you listen to events on objects that get dynamically added to the DOM. To accomplish something similar without jQuery you can attach the event handler on an element as you add it to the DOM:

// With jQuery
// Handle click events .search-result elements, 
// even when they're added to the DOM programmatically
$(".search-container").on("click", ".search-result", handleClick);

// Without jQuery
// Create and add an element to the DOM
var searchElement = document.createElement("div");
document.querySelector(".search-container").appendChild(searchElement);
// Add an event listener to the element
searchElement.addEventListener("click", handleClick);

Triggering and creating events

The equivalent to manually triggering events with trigger() can be achieved by calling dispatchEvent(). The dispatchEvent() method can be invoked on any element, and takes an Event as the first argument:

// With jQuery
// Trigger myEvent on document and .box
$(document).trigger("myEvent");
$(".box").trigger("myEvent");

// Without jQuery
// Create and dispatch myEvent
document.dispatchEvent(new Event("myEvent"));
document.querySelector(".box").dispatchEvent(new Event("myEvent"));

Styling elements

If you’re calling .css() on an element to change its inline CSS with jQuery, you’d use .style in JavaScript and assign values to its different properties to achieve the same effect:

// With jQuery
// Select .box and change text color to #000
$(".box").css("color", "#000");

// Without jQuery
// Select the first .box and change its text color to #000
document.querySelector(".box").style.color = "#000";

With jQuery, you can pass an object with key-value pairs to style many properties at once. In JavaScript you can set the values one at a time, or set the entire style string:

// With jQuery
// Pass multiple styles
$(".box").css({
  "color": "#000",
  "background-color": "red"});

// Without jQuery
// Set color to #000 and background to red
var box = document.querySelector(".box");
box.style.color = "#000";
box.style.backgroundColor = "red";

// Set all styles at once (and override any existing styles)
box.style.cssText = "color: #000; background-color: red";

hide() and show()

The .hide() and .show() convenience methods are equivalent to accessing the .style property and setting display to none and block:

// With jQuery
// Hide and show and element
$(".box").hide();
$(".box").show();

// Without jQuery
// Hide and show an element by changing "display" to block and nonedocument.querySelector(".box").style.display = "none";
document.querySelector(".box").style.display = "block";

Document ready

If you need to wait for the DOM to fully load before e.g. attaching events to objects in the DOM, you’d typically use $(document).ready() or the common short-hand $() in jQuery. We can easily construct a similar function to replace it with by listening to DOMContentLoaded:

// With jQuery
$(document).ready(function() { 
  /* Do things after DOM has fully loaded */
});

// Vanilla
document.addEventListener('DOMContentLoaded', function() {
  // code
})

// Without jQuery
// Define a convenience method and use it
var ready = (callback) =>{
  if (document.readyState != "loading") callback();
  else document.addEventListener("DOMContentLoaded", callback);
}

ready(() =>{ 
  /* Do things after DOM has fully loaded */ 
});

Working with classes

You can easily access and work with classes through the classList property to toggle, replace, add, and remove classes:

// With jQuery
// Add, remove, and the toggle the "focus" class$(".box").addClass("focus");
$(".box").removeClass("focus");
$(".box").toggleClass("focus");

// Without jQuery
// Add, remove, and the toggle the "focus" classvar box = document.querySelector(".box");
box.classList.add("focus");
box.classList.remove("focus");
box.classList.toggle("focus");

If you want to remove or add multiple classes you can just pass multiple arguments to .add() and .remove():

// Add "focus" and "highlighted" classes, and then remove themvar box = document.querySelector(".box");
box.classList.add("focus", "highlighted");
box.classList.remove("focus", "highlighted");

If you’re toggling two classes that are mutually exclusive, you can access the classList property and call .replace() to replace one class with another:

// Remove the "focus" class and add "blurred"document.querySelector(".box").classList.replace("focus", "blurred");

Checking if an element has a class

If you only want to run a function depending on if an element has a certain class, you can replace jQuery’s .hasClass() with .classList.contains():

// With jQuery
// Check if .box has a class of "focus", and do somethingif ($(".box").hasClass("focus")) {
  // Do something...
}

// Without jQuery
// Check if .box has a class of "focus", and do somethingif (document.querySelector(".box").classList.contains("focus")) {
  // Do something...
}

Network requests with .get() , .post() or .ajax()

Using GET

// jQuery
$.get('//example.com', function (data) {
  // code
})

// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.open('GET', url)
httpRequest.send()

Using POST

// jQuery
$.post('//example.com', { username: username }, function (data) {
  // code
})

// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
httpRequest.open('POST', url)
httpRequest.send('username=' + encodeURIComponent(username))

Using JSONP

// jQuery
$.getJSON('//openexchangerates.org/latest.json?callback=?', function (data) {
  // code
})

// Vanilla
function success(data) {
  // code
}
var scr = document.createElement('script')
scr.src = '//openexchangerates.org/latest.json?callback=formatCurrency'
document.body.appendChild(scr)

feth() lets you create network requests in a similar fashion to jQuery’s ajax() and get() methods. fetch() takes a URL as an argument, and returns a Promise that you can use to handle the response:

// With jQuery
$.ajax({
    url: "data.json"}).done(function(data) {
    // ...
  }).fail(function() {
    // Handle error
  });

// Without jQuery
fetch("data.json")
  .then(data =>{
    // Handle data
  }).catch(error =>{
    // Handle error
  });

Creating elements

If you want to dynamically create an element in JavaScript to add to the DOM you can call createElement() on document and pass it a tag name to indicate what element you want to create:

// Create a div & span$("<div/>");
$("<span/>");

// Create a div and a span
document.createElement("div");
document.createElement("span");

If you want to add some content to those elements, you can simply set the textContent property, or create a text node with createTextNode and append it to the element:

var element = document.createElement("div");
element.textContent = "Text"// or create a textNode and append it
var text = document.createTextNode("Text");
element.appendChild(text);

Updating the DOM

If you’re looking to change the text of an element or to add new elements to the DOM chances are that you’ve come across innerHTML(), but using it may expose you to cross-site scripting (XSS) attacks. Although you can work around it and sanitize the HTML, there are some safer alternatives.

If you’re only looking to read or update the text of an element, you can use the textContent property of an object to return the current text, or update it:

// With jQuery
// Update the text of a .button
$(".button").text("New text");
// Read the text of a .button
$(".button").text(); // Returns "New text"// Without jQuery
// Update the text of a .button
document.querySelector(".button").textContent = "New text";
// Read the text of a .button
document.querySelector(".button").textContent; // Returns "New text"

If you’re constructing a new element, you can then add that element to another element by using the method on the parent appendChild():

// Create div element and append it to .container
$(".container").append($("<div/>"));

// Create a div and append it to .container
var element = document.createElement("div");
document.querySelector(".container").appendChild(element);

Put together, here’s how to create a div, update its text and class, and add it to the DOM:

// Create a div
var element = document.createElement("div");

// Update its class
element.classList.add("box");

// Set its text
element.textContent = "Text inside box";

// Append the element to .container
document.querySelector(".container").appendChild(element);

If you want to clone an element

// jQuery
var clonedElement = $('#about').clone()

// Vanilla
var clonedElement = document.getElementById('about').cloneNode(true)

Or if you want to wrap an element

// jQuery
$('#wrap').empty()

// Vanilla
var wrap = document.getElementById('wrap')
while(wrap.firstChild) wrap.removeChild(wrap.firstChild)

In summary

This is by no means a comprehensive guide to any of the native JavaScript methods utilized here, but We hope it’s been helpful a guide if you’re looking to move away from jQuery. In summary, here are the methods that we’ve covered:

 
by Luigi Nori Date: 29-08-2019 jquery vanilla es6 hits : 1305  
 
Luigi Nori

Luigi Nori

Lavora in Internet dal 1994 (praticamente una mummia), specializzato in tecnologie Web fa felici i suoi clienti smanettando con applicazioni su larga scala e ad alta disponibilità, frameworks php e js, disegno web, intercambio dati, sicurezza, e-commerce, amministrazione database e server, hacking etico. Convive felicemente con @salvietta150x40, nel (poco) tempo libero cerca di addomesticare un piccolo nano selvaggio appassionato di astri.

 
 
 

Related Posts

    Is jQuery going to die in 2019?

    For a while, JQuery's relevance has been a topic of debate among web developers. We were curious as web developers interested in Javascript to know what others have to say…

    Best 5 Javascript NewsTicker Plugins

    Not all developers know the marquee tag of HTML, that allows you to create a scrolling piece of text or image displayed that is shown horizontally or vertically on the DOM.…

    Working with JSON in JavaScript

    JSON is short for JavaScript Object Notation and an easy - to - access way to store information. In short, it gives us a collection of human - readable data…

    Top 10 JavaScript Books 2019

    Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications. If you're an aspiring web developer then…

    6 JavaScript Utility Libraries you Should Know in 2019

    Nowadays Javascript is the most popular and widely used programming language, so the ecosystem around it constantly grows. However, it is expected that the small "standard library" of Javascript will remain…

    10 JavaScript podcasts for web developers

    1. Syntax.fm  Full Stack Developers Wes Bos and Scott Tolinski dive deep into web development topics, explaining how they work and talking about their own experiences. They cover from JavaScript frameworks…

    JavaScript Manual for Beginners

    The JavaScript Manual shows you how to use JavaScript and gives an overview of the language. I   GETTING STARTED ABOUT Created by Netscape in 1995 as an extension of HTML for Netscape Navigator…

    Top JavaScript Libraries in 2018

    As Javascript remains the most popular and widely used programming language in 2018, so grows the ecosystem around it. JavaScript has gained immense popularity over the span of a few years.…

    30 Reference Guides for JavaScript: jQuery, Node.js, and React

    This is a list intended to introduce new developers to JavaScript (jQuery, Node.js and React) and help experienced developers learn more.   jQuery jQuery API (Official) View → jQuery Cheatsheet (Devhints) View → jQuery Cheat Sheet (JavaScript Toolbox) View → jQuery Quick…

    Useful jQuery code snippets for responsive websites

    When you have to manage a web project, jQuery can be of great help. In this article, we have compiled some jQuery tips and tricks for making and enhancing responsive…

    15 Awesome Plugins for Creating Sticky Elements

    It is now common to use some fixed elements on a site when you scroll up or down. This allows for the element to be readily available regardless of the user’s…

    Fetch API, an amazing replacement of XMLHttpRequest AJAX

    When AJAX came to the modern web, it changed the definition of how web works. We all are using ajax for a long time but not with Fetch API. To…