When should I use .removeChild() vs .hidden?


When should I use .removeChild() vs .hidden?


We can use .removeChild() to remove a specified child element from a parent element to remove the element from the DOM entirely when the element is no longer needed; because the element is completely removed there will be no reference to the element. We can however store the removed child node to a variable if we need to reference it again as .removeChild() returns the removed node.

For example, given the following HTML/JS:

<!DOCTYPE html>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>My Site</title>
<div class="parent">
  <p class="child">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>


let parent = document.querySelector('.parent');
let child = document.querySelector('.child');
let referenceToRemovedChild = parent.removeChild(child);

The referenceToRemovedChild variable will be assigned to the entire child node that was removed via .removeChild().

We can use .hidden instead when we need to hide an element that we may need at a later time when the content is relevant or if we need to hide content when it is no longer relevant. Using .hidden will not remove the node it’s used on unlike parentNode.removeChild(childNode);. We can still access and modify the hidden element.