Selecting, manipulating, and events
| Command | Description |
|---|---|
document.getElementById("id") | Select by ID |
document.querySelector(".class") | Select first match |
document.querySelectorAll("div") | Select all matches (NodeList) |
el.closest(".container") | Find closest ancestor |
| Command | Description |
|---|---|
el.innerHTML = "<span>Hi</span>" | Set HTML content |
el.textContent = "Text" | Set text content |
el.classList.add("active") | Add class |
el.classList.remove("hidden") | Remove class |
el.classList.toggle("open") | Toggle class |
el.setAttribute("src", "img.jpg") | Set attribute |
el.style.color = "red" | Set inline style |
| Command | Description |
|---|---|
document.createElement("div") | Create element |
parent.appendChild(el) | Add to end of parent |
parent.prepend(el) | Add to start of parent |
el.remove() | Remove element |
| Command | Description |
|---|---|
el.addEventListener("click", fn) | Attach event listener |
el.removeEventListener("click", fn) | Remove listener |
e.preventDefault() | Prevent default action |
e.stopPropagation() | Stop bubbling |
document.addEventListener("DOMContentLoaded", fn) | DOM ready |