Remove a div element with Javascript when a button is clicked

I am working on a project where I need to dynamically add and remove divs from a webpage. These divs contain inner divs, and while the functionality to add new divs is working fine for me, I'm facing some issues with removing them.

The code snippet below shows how I can successfully add new divs:

<!--This function appends all elements required to create a new step inside the answer_step div-->
    $("button.add_answer_step_button").click(function () {
        $new_step = $("div.answer_steps")
            .append($('<div id = answer_step_' + answer_identifier_number + ' class = "answer_step">')
            .append($('<div class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question">'))
            .append($('<div class = "answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step">'))
            .append($('<button class = "remove_answer_step_button">- Remove This Step</button>')));

        <!--Increment identifier number by 1-->
        answer_identifier_number++;
    });

However, when it comes to removing these added divs, I encountered a challenge. Below is the code block that I believe should work but isn't functioning as expected:

$("#remove_answer_step_button").click(function () {
        $(this).parent().remove();
    });

I have also created a fiddle for demonstration: https://jsfiddle.net/max_m/5r07utj1/

The issue seems to be related to the removal of subsequent divs that are added to the page. Although the code works locally for the first div, it fails for others. However, I managed to find a solution by modifying the code as shown below:

$(document).on('click','.remove_answer_step_button', function () {
        $(this).parent().remove();
    });

Answer №1

If you're looking for a complete working example of what you're trying to achieve, check out the code below. I've integrated ko bindings into your existing code to enhance its functionality. While there is a more concise way of achieving this in terms of HTML structure, I opted for clarity over brevity.

The error occurring in the code snippet puzzles me since it runs flawlessly on the fiddle provided.

https://jsfiddle.net/RachGal/na38tmog/

answer_identifier_number = 0;

$(document).on('click', '.add_answer_step_button', function() {
  $new_step = $("#answer_steps").append($('<div id="answer_step' + answer_identifier_number + '" class = "answer_step draggable" data-bind="draggable:true,droppable:true">').append($('<div id="answer_step_equation' + answer_identifier_number + '" class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question">')).append($('<div id="answer_step_description' + answer_identifier_number + '" class = "answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step">')).append($('<div class="buttons"><button class = "remove_answer_step_button">- Remove This Step</button><button class = "add_answer_step_button">+Add Next Step</button></div>'));

  answer_identifier_number++;
});
var no_children = $('.answer_step_equation').length;

if (no_children == 1) {
  $('.remove_answer_step_button').attr('disabled', true);
  $('.remove_answer_step_button').css("visibility", "hidden");
}

$(document).on('click', '.remove_answer_step_button', function() {
  $(this).parent().parent().remove();
});

var draggableArguments = {
  revert: 'invalid',
  helper: 'clone',
  appendTo: '#answer_steps',
  refreshPositions: true,
  containment: 'parent',
  zIndex: 1500,
  addClasses: false
};

$('#answer_steps').sortable();


var count = 0;
var selectedDraggable;

ko.bindingHandlers.draggable = {
  init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
    $(element).draggable();
    var list = valueAccessor();
    $(element).sortable({
      update: function(event, ui) {
        //retrieve our actual data item
        var answer_step = ko.dataFor(ui.answer_step.get(0));
        //figure out its new position
        var position = ko.utils.arrayIndexOf(ui.answer_step.parent().children(), ui.answer_step[0]);
        //remove the item and add it back in the right spot
        if (position >= 0) {
          list.remove(answer_step);
          list.splice(position, 0, answer_step);
        }
        ui.answer_step.remove();
      }
    });
    $(element).on('click', function() {
      selectedDraggable = $(this);
    });
  }
};

var vm = function() {
  var self = this;
  self.answer_steps = ko.observableArray();
  self.answer_step = ko.observable('');
  self.init = function() {
    self.answer_steps([]);
  };
  self.remove = function(answer_step) {
    self.answer_steps.remove(answer_step);
  };
  self.addNew = function() {
    self.answer_steps.push(self.answer_step());
    self.answer_step('');
  };
  self.init();
};

ko.applyBindings(new vm());
#answer_steps {
  display: block;
  margin-top: 40px;
  width: 100%;
}
.answer_step {
  display: block;
  position: relative;
  width: 98%;
  height: 200px;
}
.draggable {
  border: solid 1px gray;
}
#buttons {
  width: 98%;
  display: block;
}
.answer_step_equation {
  float: left;
  border: 1px solid black;
  background-color: #F0F4F5;
  width: 60%;
  height: 150px;
  margin-top: 20px;
  margin-bottom: 5px;
  text-align: left;
  overflow-x: hidden;
  overflow-y: auto;
}
.answer_step_description {
  float: right;
  border: 1px solid black;
  background-color: #F0F4F5;
  width: 38%;
  height: 150px;
  margin-top: 20px;
  margin-bottom: 5px;
  text-align: justify;
  overflow-x: hidden;
  overflow-y: auto;
}
[contenteditable=true]:empty:not(:focus):before {
  content: attr(placeholder);
  color: #96ADB5;
  text-align: justify;
  font-size: 14pt;
  font-style: italic;
  display: block;
}
button.add_answer_step_button {
  float: right!important;
  width: 200px;
  height: 25px;
  font-size: 12pt;
  font-weight: bold;
  border-radius: 5px;
  background-color: #eee;
  color: #444;
  border: solid 1px gray;
}
button.remove_answer_step_button {
  display: block;
  visibility: visible;
  float: left;
  width: 200px;
  height: 25px;
  font-size: 12pt;
  font-weight: bold;
  border-radius: 5px;
  background-color: #eee;
  color: #444;
  border: solid 1px gray;
}
button.add_answer_step_button:active,
button.add_answer_step_button:hover,
button.remove_answer_step_button:active,
button.remove_answer_step_button:hover {
  background-color: #CDEDF7;
  border: 1px solid blue;
  cursor: pointer;
}
<!doctype html>
<html>
<head>
<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="center_column" id="center_column">
  <!--Put in the Plus Sign, Equation and text instruction to allow the user to add a new Div to write the solution and directions-->
  <div id="answer_steps" class="answer_steps" data-bind="foreach:answer_steps">

    <!--Div contains each answer step-->
    <div id="answer_step" class="answer_step draggable" data-bind="draggable:true,droppable:true">
      <!--This placeholder text will empty the div once the user starts typing-->
      <div id="answer_step_equation" class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question"></div>
      <div id="answer_step_description" class="answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step"></div>
      <!-- Buttons to dynamically add and remove answer divs. The remove functionality is added in JQuery for the add button-->
      <div class="buttons">
        <button class="add_answer_step_button">+ Add next Step</button>
        <button class="remove_answer_step_button">- Remove This Step</button>
      </div>
    </div>
  </div>
</div>
  </body>
  </html>

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

Unable to set an onclick function within a customized dojo widget

I have a custom widget that I've defined as shown below: dojo.declare('myWidget', [dijit._WidgetBase, dijit._Templated], { 'templateString':'<span>' + '<a dojoAttachPoint="linkNode" href="b ...

What is the best way to make HTML adjust to SVG scaling?

After applying a scale transform to an SVG, I noticed that the surrounding HTML does not adjust its size accordingly. Here is the SVG in question: <div> <svg height="300" width="300" viewbox="0 0 300 300" transform="scale(1.55)" xmlns= ...

Unable to send headers to the client in expressjs as they have already been set

After successfully logging in, I am trying to redirect to another page but keep encountering the error message "Cannot set headers after they are sent to the client". I understand that I need to place the res.redirect method somewhere else in my code, bu ...

Ensuring the Angular Material bottom sheet (popover) stays attached to the button

Recently, I've been working on an Angular project where I successfully integrated a bottom sheet from Angular Material. However, I encountered an issue when trying to make the opened popup sticky to the bottom and responsive to its position, but unfor ...

problem arises when I attempt to use the code individually, as well as when I incorporate it into my existing

<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <title>App Title</title> <!-- Framework's CSS Fil ...

Styling with CSS and using templates

Just had a quick question about CSS and a template I'm working with. Currently, I have these two fields in my CSS: .content { padding:10px; width: 100% text-align:justify; font: 9pt/14pt 'Lucida Grande', Verdana, Helvetica, sans-serif; } ...

Chrome experiences a hidden stalling issue due to a large WebGL texture

While working with WebGL on Windows 10 using Three.js, I noticed that initializing a large (4096 x 4096) texture causes the main thread of Chrome to stall for a significant amount of time. Surprisingly, the profiler doesn't show any activity during th ...

Issues with Ul List Alignment (CSS and HTML)

<div class="companies"> <ul class="logos"> <li><img src="images/image1.png" alt="" height="25px" /></li> <li><img src="images/image2.png" alt="" height="25px" /></li> <li> ...

What steps should I follow to make a stunning photo collage using HTML, CSS, and Bootstrap?

I attempted to insert images into the div but encountered difficulties. <img class="img-fluid" src="https://via.placeholder.com/800x800" style="border-radius: 20px" ...

Implementing jQuery UI toggleClass method to seamlessly alternate between two distinct CSS classes

My goal is to toggle between two CSS classes on a selector click using Jquery UI .toggleClass(), but unfortunately, it's not producing the desired toggle effect. $(".toggle").click(function () { $(".archivePosts .columns").removeClass( "l ...

There seems to be a problem with Bootstrap 4 Nav-tabs when forms are added inside them, causing

Previously, when the content consisted only of text and you clicked on the nav-tabs link, it displayed the necessary information. However, after adding these forms, the functionality stopped working. It seems like the issue lies with form integrations. Her ...

Determine the value from an object in the view by evaluating a string in dot notation

Seeking assistance with a recurring issue I've encountered lately. Imagine having two objects in AngularJS: $scope.fields = ['info.name', 'info.category', 'rate.health'] $scope.rows = [{ info: { name: "Apple", cate ...

Why are the icon pictures not displaying in Angular's mat-icon-button?

Recently, I stumbled upon a snippet of code in an Angular project that caught my eye. Naturally, I decided to incorporate it into my own program: <div style="text-align:center"> <a mat-icon-button class="btn-google-plus" href="http://google.com ...

Connect Angular Material by chaining together md-select elements from arrays and array of form inputs

I am encountering a challenge with combining chains in Angular Material. I aim to transition from this linked solution on jsfiddle to using md-select and md-option in Material. How should it function? It's quite simple. Here's the scenario: Se ...

A guide on transferring and transforming text data on the server

While I have a basic understanding of php, ajax, and javascript (including jQuery), I am still a beginner and could use some assistance with connecting the dots for this simple task: My goal is to allow the user to input text (for example: "I saw the sun, ...

Troubleshooting the Create Order Issue: Integrating PayPal Checkout with Smart Payment Buttons using React and Redux

Every time I attempt to process a payment, I encounter a 422 error: Unprocessable entity. The issue arises when I try to dynamically capture the purchased item details received from the redux store. I tried following this example (duplicate): PayPal Check ...

Struggling to properly send props to the child component in Vue 3

Is there a way to pass data from the request through axios in the root component to the child using Vue? Currently, only the "title" field is displayed correctly, but I also need to output the "body". Note: This is my first time working with Vue and I&apo ...

Could you provide me with a demonstration of cross-domain functionality?

Similar Inquiry: Methods to bypass the same-origin policy Let's consider two domains for this example - "" and "". The first domain "" is generating data in JSON format as shown below: { "str_info": [ { "str_name": "Mark ...

Optimal method for file uploading with Node.js

How can I effectively manage file uploads in node js? I would like users to be able to upload profile images with the following specifications: -Validated size of at least 200 * 200 -Accepted file formats are png, jpg, jpeg, or gif -Additional functi ...

What steps can be taken to activate a class upon a click event?

I have successfully implemented a hover function to change the background color on my element, but now I need to add an additional functionality to make the class active on click event as well. I have been struggling to find a solution for this issue and ...