JavaScript DOM Manipulation
Discover how to dynamically change the content and styles of your web pages using JavaScript DOM manipulation techniques. Click on the code snippets below to copy them and enhance your projects instantly.
Changing text content of an element
const header = document.querySelector('h1');
header.textContent = 'Welcome to My Page';
Appending new elements to the DOM
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a dynamically added paragraph.';
document.body.appendChild(newParagraph);
Removing elements from the DOM
const oldParagraph = document.querySelector('.old-paragraph');
if (oldParagraph) {
oldParagraph.remove();
}
Adding event listeners to elements
const button = document.querySelector('button');
button.addEventListener('click', () => {
alert('Button was clicked!');
});
Toggling classes on elements
const toggleClassElement = document.querySelector('.toggle-class');
toggleClassElement.addEventListener('click', () => {
toggleClassElement.classList.toggle('active');
});
Dynamically updating CSS styles of elements
const styleElement = document.querySelector('.style-update');
styleElement.style.color = 'blue';
Creating new elements on the fly
const newDiv = document.createElement('div');
newDiv.className = 'new-div';
newDiv.textContent = 'I am a new div!';
document.body.appendChild(newDiv);
Traversing the DOM tree
const parentElement = newDiv.parentNode; console.log('Parent Element:', parentElement);
Manipulating form elements
const inputField = document.querySelector('input[type="text"]');
inputField.value = 'New input value';
Animating elements on the page
const animatedElement = document.querySelector('.animate-me');
animatedElement.style.transition = 'transform 0.5s';
animatedElement.style.transform = 'translateX(100px)';