Advanced DOM manipulation in JavaScript involves more complex interactions with the Document Object Model, including creating, modifying, and animating elements, handling events, and working with more advanced techniques. Let's explore some advanced DOM manipulation concepts with examples:
1. Creating Elements:
const newDiv = document.createElement('div');
newDiv.className = 'new-div';
newDiv.textContent = 'This is a new div element.';
document.body.appendChild(newDiv);
2. Modifying Elements:
const existingDiv = document.querySelector('.existing-div');
existingDiv.textContent = 'Updated content';
existingDiv.classList.add('highlight');
3. Cloning Elements:
const originalDiv = document.querySelector('.original-div');
const clonedDiv = originalDiv.cloneNode(true);
document.body.appendChild(clonedDiv);
4. Event Delegation:
document.addEventListener('click', event => {
if (event.target.matches('.clickable')) {
console.log('Clicked on a clickable element:', event.target);
}
});
5. Animations with CSS Transitions:
<style>
.fade {
opacity: 0;
transition: opacity 1s ease-in-out;
}
</style>
<div class="fade">Fading Element</div>
<script>
const fadeElement = document.querySelector('.fade');
setTimeout(() => {
fadeElement.style.opacity = 1;
}, 1000);
</script>
6. Animations with requestAnimationFrame:
function animateElement() {
const element = document.querySelector('.animated');
let position = 0;
function step() {
position += 2;
element.style.left = position + 'px';
if (position < 200) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
7. Creating Complex UI Components:
class Accordion {
constructor(container) {
this.container = container;
this.headers = this.container.querySelectorAll('.accordion-header');
this.headers.forEach(header => {
header.addEventListener('click', () => this.togglePanel(header));
});
}
togglePanel(header) {
const panel = header.nextElementSibling;
panel.classList.toggle('active');
}
}
const accordionContainer = document.querySelector('.accordion-container');
const accordion = new Accordion(accordionContainer);
8. Virtual DOM Manipulation with Libraries (React, Vue):
Using libraries like React or Vue.js can simplify complex DOM manipulation scenarios by abstracting away direct manipulation and providing a virtual DOM that optimizes updates
Top comments (0)