I aim to utilize vanilla JavaScript in order to remove the parent element of the button being clicked when the user interacts with it

My latest project involves a meme generator that allows users to input text and images, which are then combined to create a unique 'meme'. Each meme is assigned a unique ID and features buttons for deleting the meme upon hovering. To achieve this functionality, I utilized vanilla JS and layered multiple child divs (image, top text, bottom text) using z-index.

Despite my efforts, I'm facing challenges with enabling the delete button to remove the parent div on click. I aim to have the delete button effectively remove the entire meme - image, text, and button itself. You can view an example picture and code snippets below:

https://i.sstatic.net/dIJWP.jpg

I attempted to implement the deletion feature in vanilla JavaScript by assigning a 'closeTheMeme' function to each delete button:

let deleteBtns = document.getElementsByClassName('.delete');

function closeTheMeme (){
    this.parentElement.parentElement.removeChild();
};

for(let i=0;i<deleteBtns.length;i++){
    deleteBtns[i].addEventListener("click",closeTheMeme);
}

No errors were reported in the console. Below, you'll find the remaining JavaScript code depicting how elements are generated upon clicking the meme generator.

'use strict';

let count=0;

// SUBMIT FORM
document.getElementById('memeInput').addEventListener('submit',function(e){
    count++;
    //prevent default
    e.preventDefault();
    //set image, top, and bottom texts to variables for manipulation
    let bottomText = document.getElementById('bottomText').value;
    createMeme();    
})

function createMeme(){
        let meme = document.createElement("DIV");
        document.body.appendChild(meme);
        meme.setAttribute("id", "meme"+count);

        let img = document.createElement("IMG"); 
        img.setAttribute("id","image"+count);
        let imageLink = document.getElementById('imageLink').value;
        meme.appendChild(img);
        document.getElementById("image"+count).src=imageLink;  

        let topText = document.getElementById('topText').value;
        let top = document.createElement('DIV');
        top.setAttribute("id","topText"+ count);
        meme.appendChild(top);
        top.innerHTML = topText;

        let bottomText = document.getElementById('bottomText').value;
        let bottom = document.createElement('DIV');
        bottom.setAttribute("id","bottomText" + count);
        meme.appendChild(bottom);
        bottom.innerHTML = bottomText;

        let deleteButton = document.createElement("BUTTON");
        deleteButton.classList.add("delete");
        deleteButton.innerHTML = "Delete";
        meme.appendChild(deleteButton);

        meme.classList.add("meme");
        top.classList.add("topWords");
        bottom.classList.add("bottomWords");

};

let deleteBtns = document.getElementsByClassName('.delete');

function closeTheMeme (){
    this.parentElement.parentElement.removeChild();
};

for(let i=0;i<deleteBtns.length;i++){
    deleteBtns[i].addEventListener("click",closeTheMeme);
}

Answer №1

Upon loading the page, you must manually select the buttons to enable functionality. If no buttons exist, there is nothing for events to be attached to, resulting in non-functioning buttons.

To resolve this issue, create the buttons first and then add event handlers to them.

const deleteButton = document.createElement("BUTTON");
deleteButton.addEventListener("click", function () {
  this.closest("div").remove();
});

Another approach is to use event delegation.

document.body.addEventListener("click", function (e) {
  const btn = e.target.closest(".delete");
  if (btn) btn.closest("div").remove();
});

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

Ensuring various conditions with ngIf

I've created a toggle function that updates the text of a link, but I'm struggling to handle multiple conditions. For example, *ngIf="condition1 or condition2". Below is an excerpt from my code: <a routerLink="/ads" class="tip" (click)="togg ...

Updating is not happening with ng-repeat trackBy in the case of one-time binding

In an attempt to reduce the number of watchers in my AngularJS application, I am using both "track by" in ngRepeat and one-time bindings. For instance: Here is an example of my view: <div ng-repeat="item in items track by trackingId(item)"> {{ : ...

The __init__() function in Django encountered an error with the unexpected keyword 'user' being passed

Currently, I am working on establishing a password reset system using the default django libraries. However, I have encountered an error trace while trying to access the site for changing passwords (PasswordChangeConfirm). Internal Server Error: /reset/con ...

Error message "Script start is missing" found in install.json for socket.io-php package

I am looking to develop a .io game that integrates with some PHP APIs, and I have been attempting to run the following files: install.json: { "name" : "workerman/phpsocket.io", "type" : "library", "keywords": ["socket.io"], "homepage": ...

Update the class of the panel immediately prior to a click event

Is it possible to change the class before the animation starts or when opening/closing the panel? Currently, the class only changes after the animation has finished and the panel is already open or closed. Here is an example: http://jsfiddle.net/0b9jppve/ ...

When watching YouTube videos in full screen mode on F11, the IFrame zooms in excessively, causing the video quality to suffer

After using the same code as the website Virtual Vacation, I noticed that they are experiencing the same issue as me. I am considering reaching out to them to inform them about it, but I am struggling to find a solution on my own. Specifically on WINDOWS ...

Enhancing Dropdown Functionality Using Jquery

Hey there, I am looking to create a dropdown list/menu similar to the one shown in this image: (a screenshot). Could you please guide me on how to achieve this? Can it be done using JQUERY? Thank you in advance, Andrea ...

Importing JavaScript files to work with Vue-Router: A Step-by-Step Guide

Seeking guidance on importing JavaScript files correctly throughout my Vue project, including within the components used to implement changes with Vue-Router. Currently, encountering an issue where I must reload the component in order for the JavaScript to ...

Using AngularJS to filter JSON data

Greetings! I possess the following JSON data: $scope.Facilities= [ { Name: "-Select-", Value: 0, RegionNumber: 0 }, { Name: "Facility1", Value: 1, RegionNumber: 1 }, { Name: ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

Enhancing Security with Subresource Integrity in Angular-Cli

Has anyone discovered a way to enable Subresource Integrity with Angular-CLI? I came across this GitHub Pull Request that suggests it may become a feature in the future: GitHub Pull Request. I tried to activate it on the current versions but had no luck. ...

Conceal All Other Divs upon Clicking on a New Div Bearing the Identical Class

I'm having trouble implementing the feature that closes other divs when I click on a new div with the same class. It seems like it should be straightforward, but for some reason, it's not working for me. Here is the link to the fiddle where I&apo ...

Capturing text content in an HTML attribute - using Selenium

In my research, I found that most questions were about extracting text from <p> ... </p> tags. However, what I am curious about is whether Selenium can be used to extract text from an HTML attribute like this: <li id="bullet" someid="1003"& ...

The object persists in revealing the password that I am attempting to conceal

Seeking help to hide the password object from being displayed. Below is my code snippet where I am using bcrypt to hash the password. Even though I am trying to hide the return object, I am not seeing the desired outcome. Can someone please point out wha ...

Issue with sticky navigation bar causing page content to shift

Any ideas on how to solve my issue with a sticky nav bar in Twitter Bootstrap? Whenever I scroll past a certain point, the navbar sticks but causes my content to jump. I want the content to stay in place without jumping. Here is my HTML code: <body> ...

The iPhone display scaling issue is causing difficulty viewing the entire website

Currently experiencing difficulties with a page that lacks sufficient content, resulting in a smaller height. As a result, the iPhone is scaling the page and cutting off the full menu bar (960px wide). I attempted to set a minimum height using a media quer ...

Using onchange within an onchange event will not function as intended

When I am in the process of creating 2 dropdown menus filled from a database, the issue arises when the second dropdown is generated after selecting a value from the first one. Upon choosing an option from the second dropdown, my ajax function is triggered ...

How to leverage onpopstate in Vuejs without relying on vue-router

I am currently utilizing vue.js in conjunction with laravel, specifically incorporating a vue component within a laravel blade file. My aim is to trigger a page reload upon pressing the back navigation button to return to the previous page. The code I have ...

What is preventing me from using javascript setInterval with a function in a separate external file?

Everything is running smoothly with this code snippet...an alert pops up every 10 seconds <script type='text/javascript'> function letsTest(){ alert("it works"); } var uptimeId = window.setInterval(letsTest, 10000); < ...

Issue with invoking controller action in MVC4 via AJAX

Below is the method in my controller: public JsonResult GetRights(string ROLE_ID) { var result = db.APP_RIGHTS_TO_ROLES.Where(r => r.FK_ROLE_ID.ToString() == ROLE_ID).Select(r => r.APP_RIGHTS).ToList(); return Json(re ...