I’m trying to create a website dashboard using html,css and javascript. In the dashboard selection menu I added few options for user to select the data want to display on the rightside webpage. For the each selection option I add a click EventListner function using forEach loop. When the user click a option I get the Id of that element and matched it with the data table id want to display. Then the adding classname .active{display: block;} to the selected element display the user selected table.
When firsttime user select elemen javascript eventListner Functio wokrs, But when user select the same element for the second time ` document.getElementById(elementId)` return null and whole program crashes.
<div class="dashboard">
<div class="menu">
<div class="menu-btns">
<a id="dashboard" class="menu-btn">Dashboard</a>
<a id="posted" class="menu-btn">Posted Jobs</a>
<a id="applicants" class="menu-btn">Applicants</a>
<a id="newJob" class="menu-btn">New Job</a>
<a id="myProfile" class="menu-btn">My Profile</a>
</div>
</div>
<div class="interface">
<div id="main-dashboard" class=""></div>
<div id="publihed-posts" class="published">
<table class="published-job-post-table active">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Published Date</th>
<th>Closing Date</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Senior Software Engineer</td>
<td>01/02/2022</td>
<td>01/02/2022</td>
<td><button class="btn btn-db-edit">Edit</button></td>
<td><button class="btn btn-db-delete">Delete</button></td>
</tr>
</tbody>
</table>
</div>
<div id="recieved-applicants" class="applicants">
<table class="recieved-application-table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Title</th>
<th>Applied Date</th>
<th>Check</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div id="vacancy-published" class="vacancy-publish">
<p class="vacancy-form-heading">Vacancy Publish Form</p>
<form class="vacany-publish-form" action="">
<div>Form Content<div/>
</form>
</div>
let dashboardBtnEl = document.querySelectorAll(".menu-btn");
let elementId;
dashboardBtnEl.forEach((btn) => {
btn.addEventListener("click", (event) => {
let selectedEl = event.target.id;
if (elementId) document.getElementById(elementId).remove("active");
switch (selectedEl) {
case "dashboard":
elementId = "main-dashboard";
break;
case "posted":
elementId = "publihed-posts";
break;
case "applicants":
elementId = "recieved-applicants";
break;
case "newJob":
elementId = "vacancy-published";
break;
case "myProfile":
elementId = "edit-profile";
break;
}
console.log(elementId);
console.log(document.getElementById(elementId);
document.getElementById(elementId).classList.add("active");
});
});
>Solution :
Your problem is here
document.getElementById(elementId).remove("active");
change it with
document.getElementById(elementId).classList.remove("active");
You are removing the matched element from the DOM


