💡 Key Takeaways
🔍 Element Selection: Use document.querySelector() or getElementById() to find elements quickly.
✏️ Content Editing: Change text or HTML with textContent and innerHTML.
🎨 Style Updates: Modify styles or toggle classes using classList.
🧩 Dynamic Elements: Create, insert, or remove DOM nodes on the fly.
⚡ Event Handling: Use addEventListener() to respond to user actions.
🧭 Selecting Elements
- Select by ID, class, or tag name
- Use
querySelector()for flexible selection querySelectorAll()returns a NodeList
const title = document.getElementById('title');
const items = document.querySelectorAll('.item');
const btn = document.querySelector('.btn');
✏️ Editing Content
- Change text with
textContent - Update HTML with
innerHTML - Read element content easily
title.textContent = 'New Title';
title.innerHTML = '<em>New Title</em>';
console.log(title.textContent);
🎨 Styling Elements
- Change inline styles directly
- Add or remove CSS classes
- Toggle visibility or highlights
btn.style.backgroundColor = 'tomato';
btn.classList.add('active');
btn.classList.toggle('highlight');
🧱 Creating & Removing Elements
- Create new elements dynamically
- Append or insert into the DOM
- Remove elements when needed
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello!';
document.body.appendChild(newDiv);
newDiv.remove();
⚙️ Attributes
- Get or set attributes easily
- Update links, sources, or alt text
- Remove attributes when unnecessary
link.setAttribute('href', 'https://example.com');
console.log(link.getAttribute('href'));
img.removeAttribute('alt');
🎧 Event Handling
- Attach events with
addEventListener() - Handle inputs, clicks, or keypresses
- Remove listeners when done
btn.addEventListener('click', () => console.log('Clicked!'));
input.addEventListener('input', e => console.log(e.target.value));
btn.removeEventListener('click', handleClick);
🔁 Traversing the DOM
- Move up and down the DOM tree
- Access children or siblings easily
- Navigate relationships programmatically
console.log(element.parentNode);
console.log(element.children);
console.log(element.nextElementSibling);