jQuery to vanilla JavaScript
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. now is probably a good time to move away from jQuery
Elements
Create 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 and a span
$("<div>");
$("<span>");
// Create a div and a span
document.createElement("div");
document.createElement("span");
Select 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");
Run a function on all elements in a selection
querySelectorAll() returns a NodeList containing all of the elements matching the query. Whereas you can run a function with jQuery on the entire selection of elements simply by calling the method on the jQuery object, however, you’ll have to iterate over the NodeList of elements using NodeList.forEach() in vanilla JavaScript:
// Hide all instances of .box
$(".box").hide();
// Iterate over the nodelist of elements to hide all instances of .box
document.querySelectorAll(".box").forEach(box => box.style.display = "none" );
Find 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:
// Select the first instance of .box within .container
var container = $(".container");
// Later...
container.find(".box");
// Select the first instance of .box within .container
const container = document.querySelector(".container");
// Later...
container.querySelector(".box")
hide() and show()
The .hide() and .show() convenience methods are equivalent to accessing the .style property and setting display to none and block:
// Hide and show and element
$(".box").hide();
$(".box").show();
// Hide and show an element by changing "display" to block and none
document.querySelector(".box").style.display = "none";
document.querySelector(".box").style.display = "block";
Traversing the tree
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:
// Return the next, previous, and parent element of .box
$(".box").next();
$(".box").prev();
$(".box").parent();
// Return the next, previous, and parent element of .box
const box = document.querySelector(".box");
box.nextElementSibling;
box.previousElementSibling;
box.parentElement;
Working with Classes
You can easily access and work with classes through the classList property to toggle, replace, add, and remove classes:
// Add, remove, and the toggle the "focus" class
$(".box").addClass("focus");
$(".box").removeClass("focus");
$(".box").toggleClass("focus");
// Add, remove, and the toggle the "focus" class
const 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 them
const 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");
Inline Styling
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:
// Select .box and change text color to #000
$(".box").css("color", "#000");
// 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:
// Pass multiple styles
$(".box").css({ "color": "#000", "background-color": "red"});
// Set color to #000 and background to red
const 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";
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.
TIP
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: If you’re constructing a new element, you can then add that element to another element by using the method on the parent appendChild() or append():
// Update the text of a .button
$(".button").text("New text");
// Read the text of a .button
$(".button").text(); // Returns "New text"
// 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";
Put together, here’s how to create a div, update its text and class, and add it to the DOM:
// Create div element and append it to .container
$(".container").append($("<div>"));
// Create a div and append it to .container
const element = document.createElement("div");
document.querySelector(".container").appendChild(element);
// or
document.querySelector(".container").append(element);
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:
$(".button").click(function(e) { /* handle click event */ });
$(".button").mouseenter(function(e) { /* handle mouseenter event */ });
$(document).keyup(function(e) { /* handle key up event */ });
document.querySelector(".button").addEventListener("click", (e) => { /* ... */ });
document.querySelector(".button").addEventListener("mouseenter", (e) => { /* ... */ });
document.addEventListener("keyup", (e) => { /* ... */ });
Event listening for dynamically added elements
// Handle click events .search-result elements,
// even when they're added to the DOM programmatically
$(".search-container").on("click", ".search-result", handleClick);
const searchElement = document.createElement("div");
document.querySelector(".search-container").appendChild(searchElement);
// Add an event listener to the element
searchElement.addEventListener("click", handleClick);