How do you add, remove, and modify HTML elements using JavaScript?
TL;DR
To add, remove, and modify HTML elements using JavaScript, you can use methods like createElement
, appendChild
, removeChild
, and properties like innerHTML
and textContent
. For example, to add an element, you can create it using document.createElement
and then append it to a parent element using appendChild
. To remove an element, you can use removeChild
on its parent. To modify an element, you can change its innerHTML
or textContent
.
// Adding an elementconst newElement = document.createElement('div');newElement.textContent = 'Hello, World!';document.body.appendChild(newElement);// Removing an elementconst elementToRemove = document.getElementById('elementId');elementToRemove.parentNode.removeChild(elementToRemove);// Modifying an elementconst elementToModify = document.getElementById('elementId');elementToModify.innerHTML = 'New Content';
Adding, removing, and modifying HTML elements using JavaScript
Adding elements
To add an HTML element, you can use the document.createElement
method to create a new element and then append it to a parent element using appendChild
.
// Create a new div elementconst newDiv = document.createElement('div');// Set its contentnewDiv.textContent = 'Hello, World!';// Append the new element to the bodydocument.body.appendChild(newDiv);
You can also use insertBefore
to insert the new element before an existing child element.
const parentElement = document.getElementById('parent');const newElement = document.createElement('p');newElement.textContent = 'Inserted Paragraph';const referenceElement = document.getElementById('reference');parentElement.insertBefore(newElement, referenceElement);
Removing elements
To remove an HTML element, you can use the removeChild
method on its parent element.
// Select the element to be removedconst elementToRemove = document.getElementById('elementId');// Remove the elementelementToRemove.parentNode.removeChild(elementToRemove);
Alternatively, you can use the remove
method directly on the element.
const elementToRemove = document.getElementById('elementId');elementToRemove.remove();
Modifying elements
To modify an HTML element, you can change its properties such as innerHTML
, textContent
, or attributes.
// Select the element to be modifiedconst elementToModify = document.getElementById('elementId');// Change its inner HTMLelementToModify.innerHTML = 'New Content';// Change its text contentelementToModify.textContent = 'New Text Content';// Change an attributeelementToModify.setAttribute('class', 'new-class');
You can also use methods like classList.add
, classList.remove
, and classList.toggle
to modify the element's classes.
const element = document.getElementById('elementId');// Add a classelement.classList.add('new-class');// Remove a classelement.classList.remove('old-class');// Toggle a classelement.classList.toggle('active');