uncertainty about the process of deleting an HTML dropdown item element

I'm in the process of building a dynamic menu that changes based on whether a user is logged in on a webpage. Check out the HTML code I've used (Bootstrap 4):

     <div class="dropdown" id="account_info">
      <button type="button" class="btn btn-elegant" id="dropdownMenuButton" data-toggle="dropdown"><i class="icon-user-circle"></i>  User</button>
      <div class="dropdown-menu" id="drop_down">

      </div>
     </div>

Here is the code to display a "Login" link or remove it if the user is already 'signed in':

var _status = vitals.dataset.user;  //getting 'cookie' information...
var _log_status = sessionStorage.getItem("logged");

  if (_status != "none") {
   if ((_log_status === null) || (_log_status === "undefined")) { 
   elem = document.getElementById("account_in");
   elem.parentNode.removeChild(elem);  //removing 'login' item
   sessionStorage.setItem("logged", "login"); 
   }  //user has 'signed in' for the first time...
  } else {
  elem_set = document.createElement("a");
  elem_set.className = "drop-down-item";
  elem_set.id = "account_in";
  elem_set.appendChild(document.createTextNode("Login"));
  document.getElementById("drop_down").appendChild(elem_set); 
  }  //checking if the 'user' cookie has passed...or not...

When the user is not 'signed in', the code for displaying the "Login" link in the dropdown menu functions correctly (in the 'else' statement). However, an error occurs when the user is 'signed in'. The error message is "Uncaught TypeError: Cannot read property 'parentNode' of null" in the line that attempts to remove the element with the id of "account_in".

I'm confused as to why the id "account_in" is being reported as 'null', since I create that element attribute...or could this error be related to something else? Any guidance would be greatly appreciated.

Answer №1

To ensure that I could run your code, I have created a snippet below. Since I do not have the vitals library, I have commented that out and used a static value instead. Additionally, I have replaced the use of sessionStorage with a static value.

While reviewing your code, I noticed an error in the comparison:

_log_status === "undefined"
should be
typeof _log_status === "undefined"
.

I have also included the if statement that I mentioned in a comment.

If this solution does not meet your requirements, please provide a runnable snippet in your question.

var _status = 'Pangit'; //vitals.dataset.user;  //retrieve passed 'cookie' information...
var _log_status;  //sessionStorage.getItem("logged");

if (_status != "none") {
  if ((_log_status === null) || (typeof _log_status === "undefined")) { 
    elem = document.getElementById("account_in");
    
    // if _status != none and _log_status is undefined, elem will not exist
    if (elem) { 
      elem.parentNode.removeChild(elem);  //remove 'login' item
    }

    //sessionStorage.setItem("logged", "login"); 
  }  //user has 'signed in' for the initial time...
} else {
  elem_set = document.createElement("a");
  elem_set.className = "drop-down-item";
  elem_set.id = "account_in";
  elem_set.appendChild(document.createTextNode("Login"));
  document.getElementById("drop_down").appendChild(elem_set); 
}  //"user" cookie has passed...OR NOT...
<div class="dropdown" id="account_info">
<button type="button" class="btn btn-elegant" id="dropdownMenuButton" data-toggle="dropdown"><i class="icon-user-circle"></i>  User</button>
<div class="dropdown-menu" id="drop_down">

</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Passport.js with a custom callback function that accepts parameters

I currently have this block of code: app.post('/login', passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }), function(req, res) { return res.redirect('/profile/&a ...

Retrieve data from a text file using ajax and then return the string to an HTML document

Just starting out with ajax, I have a text file containing number values For example, in ids.txt, 12345 maps to 54321 12345,54321 23456,65432 34567,76543 45678,87654 56789,98765 Here is the Html code snippet I am using <html><body> < ...

Utilizing commas in JavaScript

Hi everyone, I'm having an issue with printing the message "Invalid password, Must Contain:". The problem I'm facing is that when I write the code in JavaScript, the comma is being interpreted as an operator instead of a regular English comma. Th ...

Creating images with LibCanvas

Currently, I am utilizing LibCanvas for canvas drawing on my HTML page. However, I am facing difficulty in drawing an image. Can someone provide assistance with this? UPDATE: The code snippet I am using is showing the image being drawn but then it disappe ...

Transitioning from the traditional LeftNav menu style to the more versatile composability feature using Reactjs with Material-ui

Hey there, I'm facing a bit of confusion while trying to create a LeftNav menu using material-ui. I recently joined this project and updated reactjs and material-ui. Unfortunately, many things related to LeftNav in material-ui have been deprecated, ...

The code within $(document).ready() isn't fully prepared

Feeling frustrated after spending hours searching and attempting to refactor one of my old modules on a rendered Mustache template. It's like diving into code chaos. <section id="slideShow"> <script id="slideShow-template" type="text/tem ...

Obtain the accurate sequence of tr elements in the form of a jQuery object

Even though you can define tfoot before tbody in the source code, when displayed in the browser tfoot will still appear last: <table> <thead><tr><th>i get displayed first</th></tr></thead> <tfoot><t ...

Issue encountered: "An error has occurred stating that your cache folder contains files owned by root. This is likely a result of a bug present in older versions of npm. This issue arose during the execution of the

While attempting to create a new react app using the command npx create-react-app example_app, I encountered the following issue: [ Your cache folder contains root-owned files, due to a bug in previous versions of npm which has since been addressed sudo ...

Error encountered in NEXT JS: Unable to parse URL from /api/projects or Error message: Failed to connect to 127.0.0.1:3000

Currently utilizing: export const getStaticProps = async () => { export const getStaticPaths = async () => { and accessing my API (pages/api/projects/) created with Next.js on my local host const res = await fetch("http://localhost:3000/api/ ...

Making certain parts of a select list text bold while keeping others in normal font in React

I need to create a select list that displays various products with their names and a count in bold. Here's my approach: To achieve this, I am populating an array called productInformation with each product name and its corresponding count like this: ...

What could be causing the Fontawsome icon to malfunction within a Bootstrap table item?

I am currently utilizing Fontawsome free version 5.15.4, along with Bootstrap 5.1 to develop a table using JavaScript. let newBtn = createAnyElement("button", { class: "btn btn-success", onclick: "createUser(this)&q ...

Exciting jQuery animations and transitions

Is there a way in JavaScript to call function or method names using a string? For example, when writing jQuery code that applies an effect to specific targets, can the effect be dynamic and changeable by the user? I'm hoping for something like jQuer ...

Converting a string to an HTML object in Angular using Typescript and assigning it to a variable

I am facing an issue with passing HTML content from a service to a div element. I have a function that fetches HTML content as a string from a file and converts it into an HTML object, which I can see working in the console. However, when trying to assign ...

An effective method for finding a key in a multi-dimensional array or object based on its value using JavaScript and/or jQuery

I have a unique object structure that resembles the following: var data = {}; data.items = { name : 'apple', price : '$1.00' }; data.products = { name : 'banana', price : '$0.50' }; data.goods = { name : 'oran ...

Arranging elements on a webpage using Javascript

Creating a Dynamic Div Layout with JavaScript I have successfully implemented functionality wherein clicking on + opens a div and clicking on - closes it. However, I am now faced with the challenge of handling multiple divs at runtime. How can this be ach ...

Issue with displaying the glyphicon-chevron on the carousel control

Currently, I'm in the process of incorporating a straightforward modal into my gallery design. I have a slide carousel positioned at the top of the page, while at the bottom, there are thumbnails of the gallery. While the slide carousel control butto ...

Enhancing Connectivity Through Fastify and Fastify-HTTP-Proxy Integration

I'm currently utilizing fastify along with fastify-http-proxy on a VPS running Ubuntu 19.x that is equipped with three unique IPv4 addresses. I have confirmed the functionality of these IP addresses by testing them using the following example IPs: cur ...

Ensure Password is Secure (Django/Python)

I'm currently working on a small Django app for educational purposes, utilizing the built-in User model provided by Django. My focus is on learning its features and functionality. In order to interact with users, I've created custom pages that al ...

Displaying data stored in a database using JSON format with Ember

I seem to be facing a challenge once again. Let me elaborate on what I am trying to achieve. Within the teammembers template, I aim to display information about Team Members and their details from a specific team by joining 3 tables. Here is an example o ...

HTML Multi-Column List Box

Can a List Box be created with List Items displayed in Multiple Columns? I know there are other options available, but I'm curious if this is achievable using the <select> tag ...