Manipulating the DOM means reading and writing element properties. Use **textContent** (safe, no HTML) or **innerHTML** (parses HTML — XSS risk if from user input). Use **classList** methods (add, remove, toggle, contains) over `className` string manipulation. Use **style.property** for inline styles, but prefer CSS classes for maintainability.
1Understanding DOM Element Manipulation
Manipulating the DOM means reading and writing element properties. Use textContent (safe, no HTML) or innerHTML (parses HTML — XSS risk if from user input). Use classList methods (add, remove, toggle, contains) over className string manipulation. Use style.property for inline styles, but prefer CSS classes for maintainability.
Never use innerHTML with unsupported user input — it creates XSS vulnerabilities. Use textContent for user-generated content.
const el = document.querySelector('.card');
// Content
el.textContent = 'Safe text content';
// el.innerHTML = '<b>Bold</b>'; // OK for trusted content
// Classes
el.classList.add('active');
el.classList.remove('loading');
el.classList.toggle('expanded');
console.log(el.classList.contains('active')); // true2Practical Example
Here is a real-world application of DOM Element Manipulation showing how it is used in production JavaScript code.
// Attributes
const link = document.querySelector('a');
link.setAttribute('href', 'https://example.com');
link.setAttribute('target', '_blank');
console.log(link.getAttribute('href')); // https://example.com
// Data attributes
const btn = document.querySelector('[data-id]');
console.log(btn.dataset.id); // '42'3Best Practices
Follow these guidelines when working with DOM Element Manipulation:
1. Use textContent instead of innerHTML for plain text
2. Use classList.toggle() for on/off states
3. Batch style changes by adding/removing CSS classes
Tip: Never use innerHTML with unsupported user input — it creates XSS vulnerabilities. Use textContent for user-generated content.
const el = document.querySelector('.card');
// Content
el.textContent = 'Safe text content';
// el.innerHTML = '<b>Bold</b>'; // OK for trusted content
// Classes
el.classList.add('active');
el.classList.remove('loading');
el.classList.toggle('expanded');
console.log(el.classList.contains('active')); // true