DOM Manipulation

Changing Web Page Content

DOM (Document Object Model) manipulation allows you to dynamically change the content, structure, and style of web pages using JavaScript.

Once you've selected an element, you can modify its content, attributes, and styles to create interactive and dynamic user experiences.

There are several key properties and methods for manipulating DOM elements.

// Changing text content
element.textContent = 'New text';
element.innerHTML = '<strong>Bold text</strong>';

// Changing attributes
element.setAttribute('class', 'active');
element.getAttribute('id');
element.removeAttribute('disabled');

// Changing styles
element.style.color = 'red';
element.style.backgroundColor = 'yellow';
element.style.fontSize = '20px';

// Working with classes
element.classList.add('active');
element.classList.remove('hidden');
element.classList.toggle('highlight');
element.classList.contains('active'); // true/false
  • textContent - Sets/gets plain text content (safe, no HTML)
  • innerHTML - Sets/gets HTML content (can render HTML tags)
  • setAttribute/getAttribute - Work with element attributes
  • style property - Access and modify inline CSS styles
  • classList - Add, remove, toggle CSS classes easily
  • createElement/appendChild - Create and add new elements

Try DOM Manipulation

<div id="content">
  <h2 id="title">Original Title</h2>
  <p class="text">Original paragraph text.</p>
  <button id="changeBtn">Change Content</button>
  <button id="styleBtn">Change Style</button>
  <button id="addClass">Add Class</button>
</div>

Note: Security: Use textContent for user input to prevent XSS attacks. innerHTML can execute scripts.

Note: Performance: Minimize DOM manipulation in loops. Batch changes when possible.

Note: Best Practice: Use classList instead of directly modifying className for better maintainability.