How do you add, remove, and modify HTML elements using JavaScript?
TL;DR
Create elements with document.createElement(), set text with textContent, and insert them with append(), prepend(), before(), after(), or replaceWith(). Remove an element with remove(). Use classList, properties, and attributes for targeted updates. Avoid assigning untrusted strings to innerHTML; use text and DOM construction, or an appropriate HTML sanitizer when the product intentionally accepts HTML.
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. Check that both references exist and the node is still that parent's child when the DOM may change asynchronously.
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.
When intentional, trusted markup is already available as DOM nodes, replaceChildren() can replace a container without string parsing:
You can also use methods like classList.add, classList.remove, and classList.toggle to modify the element's classes.
Further reading
- MDN Web Docs: Document.createElement
- MDN Web Docs: Node.appendChild
- MDN Web Docs: Node.removeChild
- MDN Web Docs: Element.textContent
- MDN Web Docs: Element.classList
- MDN Web Docs: Element.remove