Popular use cases

How to check if element has class in JavaScript

Last updated Feb 26, 2024
<div id="box" class="active"></div>
const element = document.querySelector("#box");

// Check if hasclass
// Result is a boolean
element.classList.contains("active");
true

How to get last array element in JavaScript

Last updated Feb 28, 2024
const apps = ["phone", "calculator", "clock"];

apps.at(-1);
"clock"

How to add multiple classes to element in JavaScript

Last updated Sep 22, 2018
<div id="box"></div>
const element = document.querySelector("#box");

element.classList.add("active", "highlighted");
<div id="box" class="active highlighted"></div>

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 loop through array in JavaScript

Last updated Feb 22, 2020
const people = ["Sam", "Alex", "Charlie"];

people.forEach(person => {
  console.log(person);
});
Sam
Alex
Charlie

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");
});