Essential DOM methods, events, and manipulation techniques
Select element by ID
const element = document.getElementById("myId");
Select first matching element
const element = document.querySelector(".myClass");
Select all matching elements
const elements = document.querySelectorAll("p");
Select elements by class
const elements = document.getElementsByClassName("myClass");
Select elements by tag
const elements = document.getElementsByTagName("div");
Create new element
const div = document.createElement("div");
Create text node
const text = document.createTextNode("Hello");
Add child to element
parent.appendChild(child);
Remove child from element
parent.removeChild(child);
Replace child element
parent.replaceChild(newChild, oldChild);
Insert element before reference
parent.insertBefore(newElement, referenceElement);
Get/set HTML content
element.innerHTML = "<p>New content</p>";
Get/set text content
element.textContent = "Plain text";
Get/set visible text
element.innerText = "Visible text";
Get/set CSS classes
element.className = "class1 class2";
Manipulate CSS classes
element.classList.add("newClass");
Access inline styles
element.style.backgroundColor = "red";
Get attribute value
const value = element.getAttribute("data-id");
Set attribute value
element.setAttribute("data-id", "123");
Remove attribute
element.removeAttribute("data-id");
Check if attribute exists
const hasId = element.hasAttribute("id");
Access data attributes
const value = element.dataset.userId;
Get parent element
const parent = element.parentElement;
Get child elements
const children = element.children;
Get first child element
const first = element.firstElementChild;
Get last child element
const last = element.lastElementChild;
Get next sibling
const next = element.nextElementSibling;
Get previous sibling
const prev = element.previousElementSibling;
Add event listener
element.addEventListener("click", handleClick);
Remove event listener
element.removeEventListener("click", handleClick);
Trigger custom event
element.dispatchEvent(new Event("custom"));
Mouse click event
element.addEventListener("click", (e) => console.log("clicked"));
Double click event
element.addEventListener("dblclick", handleDoubleClick);
Mouse enter element
element.addEventListener("mouseenter", handleMouseEnter);
Mouse leave element
element.addEventListener("mouseleave", handleMouseLeave);
Key press down
element.addEventListener("keydown", handleKeyDown);
Key release
element.addEventListener("keyup", handleKeyUp);
Form submission
form.addEventListener("submit", handleSubmit);
Input value change
input.addEventListener("change", handleChange);
Element gains focus
input.addEventListener("focus", handleFocus);
Element loses focus
input.addEventListener("blur", handleBlur);
Creating and manipulating DOM elements
// Create a new list item
function createListItem(text) {
const li = document.createElement('li');
li.textContent = text;
li.className = 'list-item';
// Add click event
li.addEventListener('click', () => {
li.classList.toggle('selected');
});
return li;
}
// Add items to a list
const list = document.getElementById('myList');
const items = ['Item 1', 'Item 2', 'Item 3'];
items.forEach(item => {
const li = createListItem(item);
list.appendChild(li);
});
Handling events on dynamically created elements
// Event delegation for dynamic content
document.getElementById('container').addEventListener('click', (e) => {
// Check if clicked element is a button
if (e.target.matches('.btn')) {
console.log('Button clicked:', e.target.textContent);
}
// Check if clicked element is inside a card
if (e.target.closest('.card')) {
const card = e.target.closest('.card');
console.log('Card clicked:', card.dataset.id);
}
});
Complete form handling with validation
const form = document.getElementById('myForm');
form.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(form);
const data = Object.fromEntries(formData);
// Validation
if (!data.email || !data.email.includes('@')) {
showError('Please enter a valid email');
return;
}
// Submit data
submitForm(data);
});
function showError(message) {
const errorDiv = document.getElementById('error');
errorDiv.textContent = message;
errorDiv.style.display = 'block';
}
Navigating through DOM elements
// Find all buttons within a specific container
const container = document.querySelector('.container');
const buttons = container.querySelectorAll('button');
// Find parent with specific class
function findParentWithClass(element, className) {
let parent = element.parentElement;
while (parent) {
if (parent.classList.contains(className)) {
return parent;
}
parent = parent.parentElement;
}
return null;
}
// Get all siblings of an element
function getSiblings(element) {
const siblings = [];
let sibling = element.parentElement.firstElementChild;
while (sibling) {
if (sibling !== element) {
siblings.push(sibling);
}
sibling = sibling.nextElementSibling;
}
return siblings;
}
Creating smooth element animations
// Fade in element
function fadeIn(element, duration = 300) {
element.style.opacity = '0';
element.style.display = 'block';
let start = performance.now();
function animate(currentTime) {
const elapsed = currentTime - start;
const progress = Math.min(elapsed / duration, 1);
element.style.opacity = progress;
if (progress < 1) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
}
// Slide down element
function slideDown(element, duration = 300) {
element.style.height = '0px';
element.style.overflow = 'hidden';
element.style.display = 'block';
const targetHeight = element.scrollHeight;
let start = performance.now();
function animate(currentTime) {
const elapsed = currentTime - start;
const progress = Math.min(elapsed / duration, 1);
element.style.height = (targetHeight * progress) + 'px';
if (progress < 1) {
requestAnimationFrame(animate);
} else {
element.style.height = 'auto';
}
}
requestAnimationFrame(animate);
}
Use querySelector
for single elements and querySelectorAll
for multiple
Always remove event listeners to prevent memory leaks
Use event delegation for dynamically created elements
Prefer textContent
over innerHTML
for security
Use classList
methods instead of manipulating className