KPM KPM - 2 years ago 109
Javascript Question

Javascript removing a div by clicking on a button

I am trying to dynamically add and remove divs from a page. The divs have inner divs. I have the add functionality working and I can get the first div created to delete. My problem is that I have modified the remove div functionality and I believe it is just a syntax problem that is stopping this from working. Any pointers?

This code adds the divs I want and is working:

<!--This appends all elements necessary to complete a new step. The divs are nested within the answer_step div here -->
$("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>')));

<!--Increase identifier number by 1-->

This next code is meant to remove any div for which the remove step button is pressed. I can getting it working for the first one with a bit of code change but I believe that the code below should work for them all. I'm stuck here:

$("#remove_answer_step_button").click(function () {

I have a fiddle created for this here

The functionality to add a new div with inner divs works locally for me but not in the fiddle.

Anyway, to my main question - I can get the remove div to work for the first div that is added but not subsequent divs that are added to the page. I think it is only a syntax problem as I have taken this code from someone else here.

A solution was found:

$(document).on('click','.remove_answer_step_button', function () {

The fiddle is available here: JSFiddle Solution

Answer Source

First off you shouldn't be using an id if you are adding multiple divs.

Unlike the id selector, the class selector is most often used on several elements. This allows you to set a particular style for many HTML elements with the same class. A simple way to look at it is that an id is unique to only one element.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download