DOM Manipulation
The process of using JavaScript to dynamically change the structure, content, or style of a web page by modifying the Document Object Model.
Overview
DOM manipulation is the practice of using JavaScript to add, remove, or modify HTML elements and their attributes after a page has loaded. It's fundamental to creating interactive web applications, allowing you to respond to user actions and update the page without requiring a full page reload.
Example
javascript// Create and add elements const container = document.getElementById('container'); const newParagraph = document.createElement('p'); newParagraph.textContent = 'New paragraph'; newParagraph.className = 'highlight'; container.appendChild(newParagraph); // Modify existing elements const heading = document.querySelector('h1'); heading.textContent = 'Updated Heading'; heading.style.color = 'blue'; heading.setAttribute('data-id', '123'); // Remove elements const oldElement = document.getElementById('old'); oldElement.remove(); // Replace elements const oldDiv = document.getElementById('old-div'); const newDiv = document.createElement('div'); newDiv.textContent = 'New content'; oldDiv.replaceWith(newDiv); // Insert HTML container.innerHTML = '<p>New <strong>HTML</strong> content</p>'; // Safer alternative to innerHTML container.insertAdjacentHTML('beforeend', '<p>Safe insertion</p>'); // Clone elements const original = document.getElementById('original'); const clone = original.cloneNode(true); container.appendChild(clone);
Key Points
- Add, remove, or modify elements dynamically
- Change styles, attributes, and content
- Core of interactive web applications
- Use modern methods like append(), before(), after()
- Be cautious with innerHTML (XSS risk)
Learn More
- DOM - Document Object Model
- Document - Document object
- Event - Event handling
- MDN: Manipulating documents