Skip to content

Instantly share code, notes, and snippets.

@dorokhin
Last active August 26, 2019 21:48
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dorokhin/8d47e91676a39c04534ea9633b98dbdb to your computer and use it in GitHub Desktop.
Vanilla JS

Operations with vanilla JavaScript (YOU MIGHT NOT NEED JQUERY)

Selecting elements

// Instead, select the first instance of .box
document.querySelector(".box");
// …or select all instances of .box  
document.querySelectorAll(".box");

Running a function on all elements in a selection

// 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

// 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()

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

Working with events

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

Event listening for dynamically added elements

// 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

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

Styling elements

// Select the first .box and change its text color to #000
document.querySelector(".box").style.color = "#000";
// 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()

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

Document ready

// 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

// Add, remove, and the toggle the "focus" class
var 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
var 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

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

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

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

Creating elements

// 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

// 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 a div and append it to .container
var element = document.createElement("div");
document.querySelector(".container").appendChild(element);
// 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);

This is by no means a comprehensive guide to any of the native JavaScript methods utilized here, but I 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:

© TOBIAS AHLIN

Also see YOU MIGHT NOT NEED JQUERY

JavaScript CheatSheet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment