Javascript dom manipulation
Created By: chatGPT
The Document Object Model (DOM) represents the structure of a document. You can use JavaScript to manipulate this structure, allowing you to add, remove, or modify elements and content on a web page dynamically.
To start manipulating the DOM, the first step is to select the elements you want to work with. You can use
document.querySelector
to select elements by CSS selectors.const element = document.querySelector('.my-class');
Once you have selected an element, you can change its content by using the
textContent
or innerHTML
properties. Use textContent
for plain text and innerHTML
for HTML content.element.textContent = 'New Text';
// or
element.innerHTML = '<span>New HTML</span>';
You can also add or remove elements from the DOM. To create a new element, use the
document.createElement
method, then append it to a parent element with appendChild
.const newDiv = document.createElement('div');
newDiv.textContent = 'Hello, World!';
const parent = document.querySelector('#parent');
parent.appendChild(newDiv);
To remove an element, use
removeChild
on its parent element.const child = document.querySelector('.child');
child.parentNode.removeChild(child);
If you want to interact with an element, you can use event listeners. For example, to respond to a click event, you can use
addEventListener
.element.addEventListener('click', () => {
alert('Element clicked!');
});
Staying mindful of performance is important. When removing multiple elements, detaching them from the DOM before processing can improve efficiency. You can use
In summary, manipulating the DOM with JavaScript allows you to create dynamic and interactive web applications. Always ensure to select, add, modify, and remove elements effectively to enhance user experience.DocumentFragment
for this purpose.const fragment = document.createDocumentFragment();
for (let i = 0; i < 5; i++) {
const newItem = document.createElement('div');
newItem.textContent = `Item ${i}`;
fragment.appendChild(newItem);
}
document.body.appendChild(fragment);