Unable to access properties of an unknown item (reading 'remove')

Can you provide guidance on how to remove the top-level parent element of a div? I've been attempting to delete the main parent element of a specific div.

element.innerHTML = `
<div class="postIt-item">
    <div class="postIt-item-btn-container"> 
    <button  class="btn-delete" type="button"><i class="fa fa-trash" aria-hidden="true></i></button>
    <button  class="btn-edit" type="button"><i class="fa fa-pencil" aria-hidden="true></i></button>
    </div>  
  <p> ${value}</p>
<div> `

const deletebtn = element.querySelector('.btn-delete');
deletebtn.addEventListener('click', deleteItem);

//delete function 
function deleteItem(e) {

  const element = e.currentTarget.parentElement.parentElement;
  e.parentElement.remove(); // 
}

Answer №1

Initially, it appears that in your innerHTML, the last div tag is not properly closed (it should be </div>).

Additionally, within the deleteItem function, e.currentTarget does not exist. Instead, you should use e.target.parentElement to access the parent node.

Lastly, why are you setting type="button" in the button element? As it is already a button element by default!

Below is an altered version of the code with the mentioned corrections:

// I added later for testing in the browser---------\
const value = "Some value here";
const element = document.createElement("div");
// -------------------------------------------------/

element.innerHTML = `
<div class="postIt-item">
  <div class="postIt-item-btn-container">
    <button class="btn-delete">Delete</button>
    <button class="btn-edit">Edit</button>
  </div>
  <p>${value}</p>
</div>
`;

document.body.appendChild(element);

const deleteButton = element.querySelector(".btn-delete");
deleteButton.addEventListener("click", deleteItem);

//delete function
function deleteItem(e) {
  const parent = e.target.parentElement;
  parent.remove();
}

Answer №2

Take a look at my experiment, first I corrected your HTML tag. The last div should be </div> instead of <div>. After that, I made some improvements to your code by making it more dynamic. I iterated over each button class in the POST section and added an event for every element.

let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. ";
    let container = document.getElementById("data");
    container.innerHTML = `
    <div id="list-post">
    <div class="postIt-item">
    POST 1
        <div class="postIt-item-btn-container"> 
        <button  class="btn-delete" type="button"><i class="fa fa-trash" aria-hidden="true"></i>Delete</button>
        <button  class="btn-edit" type="button"><i class="fa fa-pencil" aria-hidden="true"></i>Edit </button>
        </div>  
      <p> ${text}</p>
    </div> 
    
        <div class="postIt-item">
          POST 2
        <div class="postIt-item-btn-container"> 
        <button  class="btn-delete" type="button"><i class="fa fa-trash" aria-hidden="true"></i>Delete</button>
        <button  class="btn-edit" type="button"><i class="fa fa-pencil" aria-hidden="true"></i>Edit </button>
        </div>  
      <p> ${text}</p>
    </div>  
    
    </div>
    `

var buttons = document.getElementsByClassName('btn-delete');

for(var j = 0; j < buttons.length; j++){
  // Log the clicked <p> element
  buttons[j].addEventListener('click', hide, false);
}
// Log <body>

function hide(event){
  event.currentTarget.parentNode.parentElement.remove();
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet"/>
<div id="data"></div>

Does this solution meet your requirements?

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

What is the best way to modify the values in an initialized array once the fetchData method has been executed?

As a beginner in Vue.js, I am currently working on a project that involves updating initialized arrays in the data() section of my component using the fetchData method. Below is a simplified version of the code: <script> import axios from 'axi ...

What could be causing the input event not to be triggered consistently when I select or highlight text?

I have implemented a 4-digit pin field with a specific behavior: when a field is filled, the focus automatically shifts to the next field (the cursor moves to the next input field). If text in a field is deleted, the text in that field is also removed and ...

Is there a way to validate form input before inserting it into a database using the onsubmit event?

Looking for a way to enhance the verification process of my signup form, I aim to ensure that all data entered is validated before being saved in the database. The validation process involves checking if the phone number consists only of numerical values a ...

The usage of an import statement is not permissible outside of a module

Having some trouble using the mathjs library to calculate complex solutions for the quadratic equation. No matter how I try to import the library into my code, I keep encountering errors. Initially, I attempted this method: At the top of my root.js file, ...

Moving object sideways in 100px intervals

I'm struggling to solve this issue. Currently, I have multiple div elements (each containing some content) that I need to drag and drop horizontally. However, I specifically want them to move in increments of 100px (meaning the left position should b ...

Choose a random cell in Jquery every second

I am searching for a method to choose one div out of sixteen and change its CSS backgrounds. This selection needs to occur every second, so a new div is selected from the group each second. I am struggling with implementing the "every second" functionalit ...

Creating a versatile TailwindCSS grid that can adjust to varying numbers of grid columns

I am currently working with Vue3 and TailwindCSS, attempting to create a grid using a dynamic grid-cols-{n} class. While I am aware that TailwindCSS typically supports up to 12 columns by default, the challenge arises when the number of columns needed is e ...

Determine the Button's State by Monitoring Changes in the TextBox Text

I have been tasked with developing a web application for my company. The main components of the application are a button and a textbox. My goal is to allow users to input a value into the textbox, which will then be processed when they click on the button ...

When using AngularJS, encountered an issue where a view was not updating with new data from a $http request

When making a request to the 500px API using $http for popular photos, the response object is successfully returned. However, I am facing difficulty in pushing the retrieved photo items to the view. Below is my current controller code: meanApp.controller ...

The AJAX call failed because the web service was not properly configured, resulting in a missing parameter value being

I'm encountering an issue with my ajax call that displays a specific message. [WebMethod(EnableSession = true)] public static string UpdateTotalPrice(List<TicketPriceAjax> jsonTickets) { // conducting server-side processing return "a u ...

MongoDB was successfully updated, however the changes are not being displayed on the redirected

I have implemented the delete action in Node/Express as a web framework, where it is structured within a higher-level route: .delete((req, res) => { db.collection('collection-name').findOneAndDelete({ topic_title: req.body.topic_title}, ...

``There is an issue with the Nodejs required module variable not updating even after deleting

Feeling puzzled about the situation. Module 2 is supposed to require a variable from module 1, but even after deleting the cache, the variable in module 2 refuses to update when changes are made. Sample Module 1 var num = 6 function changeNum(){ num = ...

Tips for loading and updating data simultaneously in VUEJS from a single input

Currently, the data is displayed in a span tag with an input for updating it Is it possible to fetch data from an API, load it into an input field, update the input with new information, and send it back? What are the best approaches for achieving this? ...

The issue of array sorting, specifically the function(a, b) {return b.value - a.value), is causing some

I am struggling to retrieve data from firebase and sort them according to the field 'overallScore' in descending order. Despite following suggestions like using array.sort(function(a, b) {return b.value - a.value), I have not been successful in s ...

The Child/Parent arguments in Typescript methods cannot be assigned

Why is this not working in TypeScript? class Parent { id: string = '' } class Child extends Parent{ name: string = '' } const fails: (created: Parent) => void = (created: Child) => { return }; const failsToo: ({ create ...

Utilizing slug URLs effectively in Next.js

In my current project with Next.js, I am working on implementing "dynamic routes". The goal is to update the URL structure such that upon clicking, the URL should look like "myurl.com/article/55". To achieve this, I have utilized the following "link tag": ...

The sequence of divs in a language that reads from right to left

Is there a way in HTML to designate a set of divs so that they automatically align from left to right for languages that read left to right, and alternatively, flow from right to left for languages that read right to left? This means that the direction of ...

How to resolve undefined callback when passing it to a custom hook in React Native

I'm facing an issue with passing a callback to my custom hook: export default function useScreenshotDetection(onScreenshot) { useEffect(() => { ... onScreenshot(); ... }, []); } Strangely, the callback is not being detected ...

The jsonGenerator is unable to process strings containing spaces

Hey, I'm having trouble passing a string with whitespaces to my JavaScript function using jsonGenerator. Here's the code snippet: jGenerator.writeStringField(cols[8], ap.getContentId() != null ? "<img src='img/active.png' onclick=au ...

Unable to bind `this` using `call` method is not functioning as expected

Attempting to modify the Express app's .set function to be case-insensitive. For example, app.set('PORT',80); app.set('port'); // => undefined; aiming for it to return 80 Essentially, it's just a function that changes the ...