Spencer K. Spencer K. - 1 year ago 78
jQuery Question

JS: Target and remove dynamically added element

I assume this is a common problem, but I haven't been able to find the answer in other threads.

The basic idea / goal here is that if a task is marked as important, it gets added to quadrant1. If it isn't, it gets added to quadrant2. When tasks are completed, they can be closed out by clicking on them.

I have a simple page with:

  • A text input (i.e. "task")

  • Checkbox (i.e. "important")

  • Submit button (i.e. "submitTask")

  • Two divs ("quadrant1" and "quadrant2").


$(document).ready( function () {
$('#submitTask').on("click", function() {
var task = $("#task").val();
var important = $("#important").prop("checked");

var addToQuadrant = function (task, important) {
if (important == true) {
"<p class='taskHolder'> " + task + " </p>");
} else if (important == false) {
"<p class='taskHolder'> " + task + " </p>");

addToQuadrant(task, important);

$('body').on('click', '.taskHolder', function () {

My problem is that since I use the same id (i.e. "taskHolder") for both paragraph elements, if I add more than one task to my page at a time, I can't remove more than one of them.

My question is: how can I dynamically add an element to the DOM while also giving it a unique id or selector so every task can be uniquely targeted and closed out?

Answer Source



instead of


Within the event handler this references the element that the event applied to.

The following is the minimal code I'd use to implement your whole thing:

$(document).ready(function() {
  var task = $("#task");
  var cb = $("#important");
  $("button").click(function() {
    $("<p></p>", {
      text: task.val(),
      "class": "task"
    }).appendTo(cb[0].checked ? "#quadrant1" : "#quadrant2");
  $("body").on("click", ".task", function() {
    $(this).slideUp(500, function(){ $(this).remove(); });
div { border: thin black solid; margin: 4px; min-height: 20px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>Task: <input id="task"></label>
<label><input type="checkbox" id="important"> Important</label>
<div id="quadrant1"></div>
<div id="quadrant2"></div>

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