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();
});