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, 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
.
You can also use insertBefore
to insert the new element before an existing child element.
Removing elements
To remove an HTML element, you can use the removeChild
method on its parent element.
Alternatively, you can use the remove
method directly on the element.
Modifying elements
To modify an HTML element, you can change its properties such as innerHTML
, textContent
, or attributes.
You can also use methods like classList.add
, classList.remove
, and classList.toggle
to modify the element's classes.