// DOM tree ၏ root document // whole page document.documentElement // <html> element document.head // <head> document.body // <body>
// by ID
const el = document.getElementById("myId")
// by CSS selector (first match)
const el = document.querySelector("#myId")
const el = document.querySelector(".myClass")
const el = document.querySelector("h1")
const el = document.querySelector("div.card")
// by CSS selector (all matches) → NodeList
const els = document.querySelectorAll(".card")
const els = document.querySelectorAll("li")
// Older methods
document.getElementsByClassName("myClass") // HTMLCollection
document.getElementsByTagName("p") // HTMLCollection
Paragraph 1 (id="para1")
Paragraph 2 (.item)
Paragraph 3 (.item.special)
const el = document.getElementById("myDiv")
// Change text content (safe — escapes HTML)
el.textContent = "New text"
// Change HTML content (parses HTML)
el.innerHTML = "<strong>Bold text</strong>"
// Get current value
console.log(el.textContent)
console.log(el.innerHTML)
// Form input value
const input = document.getElementById("myInput")
input.value = "new value"
const current = input.value
const el = document.getElementById("box")
// Inline style
el.style.color = "red"
el.style.backgroundColor = "#f0f0f0"
el.style.fontSize = "20px"
// CSS classes
el.classList.add("active") // add class
el.classList.remove("active") // remove class
el.classList.toggle("active") // add if missing, remove if present
el.classList.contains("active") // check if has class → boolean
el.classList.replace("old", "new") // replace class
// Create element
const newDiv = document.createElement("div")
newDiv.textContent = "I'm new!"
newDiv.className = "card"
// Append to parent
const container = document.getElementById("container")
container.appendChild(newDiv) // at end
container.prepend(newDiv) // at start
container.insertBefore(newDiv, ref) // before ref element
// Modern append (can insert text too)
container.append("text", newDiv)
// Remove element
newDiv.remove() // remove self
container.removeChild(newDiv) // remove child
const link = document.querySelector("a")
// Get/Set attributes
link.getAttribute("href") // get
link.setAttribute("href", "/page") // set
link.removeAttribute("disabled") // remove
link.hasAttribute("href") // check
// Direct property access (faster)
link.href = "https://google.com"
link.id = "myLink"
img.src = "photo.jpg"
img.alt = "Photo"
input.disabled = true
input.value = "hello"
← JS 06 | Next: JS Lesson 08 → Events →