JS DOM: Remove Elements/Childen
Remove a node
node.remove()-
Remove node.
🆕 supported by browsers since 2016.
-
target_parent.removeChild(target)👎 -
- remove target.
- but you need to get target's parent in order to call. e.g.
target.parentNode.
This is old method from 2000s or before.
const xx = document.getElementById("wzm2Z"); xx.parentNode.removeChild(xx);
Replace child
🛑 warning: If the node to be inserted already exists in the same doc, it is removed from the original place and moved to the new place.
target.replaceWith(nodes, etc)-
- Replace target node by nodes.
- nodes can be a string. if so, it creates a text node.
- nodes can be many, comma separated.
🆕 supported by browsers since 2019.
-
target_parent.replaceChild(new_node, target)👎 -
- Replace the node target with new_node.
- but you need to get target's parent in order to call. e.g.
target.parentNode.
This is old method from 2000s or before.
Replace all children, or remove all children
target.replaceChildren(nodes, etc)-
- Replace all children.
- nodes can be many, comma separated.
- nodes can be a string. if so, it creates a text node.
- if no args, remove all children.
🆕 supported by browsers since 2021.
const p = document.createElement("p"); p.textContent = "hello"; document.body.replaceChildren(p);