JavaScript: DOM Cheatsheet

Here are some examples of different selector methods and approaches to updating the DOM. You can also try practicing with the interactive DOM manipulation tool.

Selector Methods

Method Example
getElementById() document.getElementById("my_element")
querySelector() document.querySelector("#my_element")
document.querySelector("p")
document.querySelector(".my-announcements")
querySelectorAll() document.querySelectorAll("p")
getElementsByTagName() document.getElementsByTagName("div")
getElementsByClassName() document.getElementsByClassName(".panel")

Some examples of HTML attributes you can modify

Attribute Example
className el.className = "panel";
innerHTML el.innerHTML = "<p>hi</p>";
src (for images) document.querySelector(".my_image").src = "sponge_bob.png";
href (for links) document.querySelector(".my_link").href = 'https://www.wikipedia.org';

Some examples of style properties you can modify

Property Example
width el.style.width = "200px";
height el.style.height = "200px";
background-color el.style.backgroundColor = "hotpink";
border-width el.style.borderWidth = "5px";
padding el.style.padding = "10px";
display el.style.display = "none";

Some useful helper functions

Property Example
insertAdjacentHTML(position, htmlString) el.insertAdjacentHTML("beforeend", "<p>stuff</p>");
insertAdjacentHTML docs
classList.add(className) el.classList.add("highlight");
classList docs
classList.remove(className) el.classList.remove("highlight");
classList.toggle(className) el.classList.toggle("highlight");

Debugging Tips

When working with DOM manipulation, here are some helpful debugging techniques:

  • Check your selectors: Use console.log(document.querySelector("#my-element")) to verify you're selecting the right element
  • Inspect elements: Right-click on elements in your browser and select "Inspect" to see the HTML structure
  • Use console.log(): Add console.log("Function called!") to verify your functions are being triggered
  • Check for typos: Common mistakes include misspelled IDs, missing quotes, or incorrect class names