It is a very simple concept but still I am writing this blog because I've made this mistake in understanding this I used .remove() every now an then, but after sometime I realized that it is very difficult to revert that.
When you use .remove()
It removes the element from the DOM, means to bring back that element you have to add the html again. Like the example given below:
Example ⇒ document.getElementById(id).innerHTML = <div>Hello</div>
note: This is one way of adding something to our existing page, Also there are other ways to do it.
When you use .style.display = “none”
It keeps the element in DOM but removes from the document/screen, so to bring back the element we just need to do ⇒ .style.display = “block”
This will keep the element in the page only but it will temporarily remove it just for your screen, If you do inspect element it will show in that, while when we use .remove(), it will entirely remove that element from the document.
When people use this?
This is most famous techniques to use when we want to make our page look visually functional, like when you click on some button it does something and gives you different view. Watch the video example for more understanding.
Video Example:
code
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Difference between .remove() & .style.display="none"</title>
</head>
<body>
<div class="container my-5 py-5">
<h1 class="text-start m-0 p-0">Example</h1>
<p><small class="text-muted mb-3 m-0 p-0">Difference between .remove() & .style.display="none"</small></p>
<div id="hide1" class="col-md-6 mb-5 bg-light rounded">
<h3>This heading is for .remove method</h3>
</div>
<div id="hide2" class="col-md-6 mb-5 bg-light rounded">
<h3>This heading is for .display method</h3>
</div>
<div class="d-flex align-items-start justify-content-start">
<button class="btn btn-primary mx-1" id="hide1btn">.remove()</button>
<button class="btn btn-primary mx-1" id="hide2btn">.style.display="none"</button>
</div>
</div>
<script>
const hide1 = document.getElementById('hide1');
const hide2 = document.getElementById('hide2');
const hide1btn = document.getElementById('hide1btn');
const hide2btn = document.getElementById('hide2btn');
hide1btn.addEventListener('click', () => {
hide1.remove();
});
hide2btn.addEventListener('click', () => {
hide2.style.display = 'none';
});
</script>
</body>
</html>
By Vishwas Acharya
THANK YOU 😉