JavaScript DOM Cheat Sheet

const element = document.getElementById("app");

Find element with id="app". We can call this function also on an element.

const elements = document.getElementsByTagName("p");

Find all "p" elements. We can call this function also on an element.

const element = document.querySelector("div.card");

Use given selector to find elements. We can call this function also on an element. There is also querySelectorAll which return all elements matching the query.

// First child of type element.
Element.firstElementChild
// Parent element, can be null, e.g. for html element.
Element.parentElement

Basic DOM navigation.

const paragraph = Document.createElement("p");
paragraph.innerText = "Lorem ipsum ...";
document.querySelector("div#app").appendChild(paragraph);

Create a paragraphs element, set the text and append it under div#app element.

const element = ...;
element.style.color = "red";

Set text CSS property "color" to "red".

const element = ...;
// Add class.
element.classList.add("important");
// Remove class.
element.classList.remove("important");
// Toggler class.
element.classList.toggle("hidden");

Working with CSS classes using JavaScript.

document.addEventListener("DOMContentLoaded", event => {
  console.log("DOM fully loaded and parsed");
});

Register a listener for DOMContentLoaded event.