Popular use cases

How to check if element has class in JavaScript

Last updated Aug 24, 2018
<div id="box" class="highlighted"></div>
const element = document.querySelector("#box");

element.classList.contains("highlighted");
true

How to interpolate in JavaScript

Last updated Nov 11, 2017
const name = "John";

console.log(`Welcome ${name}.
You have ${2 * 5} new notifications!`);
Welcome John.
You have 10 new notifications!

How to add class to element in JavaScript

Last updated Nov 11, 2017
<div id="box"></div>
const element = document.querySelector("#box");

element.classList.add("class-name");

How to replace spaces with dashes in JavaScript

Last updated Nov 11, 2017
const text = "codetogo saved me tons of time";

text.replace(/ /g, "-");
codetogo-saved-me-tons-of-time

How to reload page in JavaScript

Last updated Nov 11, 2017
window.location.reload();

How to find element by id in JavaScript

Last updated Nov 11, 2017
<div id="box"></div>
const element = document.querySelector("#box");

How to loop through array in JavaScript

Last updated Nov 11, 2017
const people = ["John", "Nicole", "Jad"];

for (const person of people) {
  console.log(person);
}
John
Nicole
Jad

How to listen to click event in JavaScript

Last updated Nov 11, 2017
<div id="box"></div>
const element = document.querySelector("#box");

element.addEventListener("click", event => {
  console.log("Element clicked");
});

How to get keys of object in JavaScript

Last updated Nov 11, 2017
const person = {
  key: "value",
  first_name: "John",
  last_name: "Doe"
};

Object.keys(person);
['key', 'first_name', 'last_name']

How to increment a variable in JavaScript

Last updated Nov 11, 2017
let counter = 0;
counter++;
1

How to uppercase a string in JavaScript

Last updated Nov 11, 2017
const text = "Hello World";

text.toUpperCase();
HELLO WORLD