0

I dynamically add the following element to the DOM.

<li id="my-link"><a href="#">Click!</a></li>

I need to keep <a href="#"> part because of styling issues (Bootstrap), and I want to delete it upon clicking it. I change the above code with

<li id="my-link"><a href="#" onclick='$(this).remove()'>Click!</a></li>

It works fine. Then, I realize that I also append another div when I append the above element, so I need to remove both of the elements. I do the following

<li id="my-link"><a href="#">Click!</a></li>
$('#my-link').click(function (e) {
  $(e.target).remove();
  $('#my-div').remove();
});

However, nothing is triggered when the click event happens. I assume href="#" is causing this issue but can someone explain exactly why this is happening? As a workaround, I could just define a function remove(), and call it through onclick='remove()', but I'd like to know why this is happening.

possible reference: link

EDIT:

<script>
  $(function() {
    var linkEl = '<li id="my-link"><a href="#">Click!</a></li>';
    var extraDiv = '<div id="my-div">Mydiv</div>';
    $('body').append(linkEl);
    $('body').append(extraDiv);
    $(linkEl).click(function (e) {
      console.log("this msg is not triggered when li is clicked. Why?");
      // delete both the link and extradiv
    });
  });
</script>

jsFiddle

Community
  • 1
  • 1
Maximus S
  • 10,759
  • 19
  • 75
  • 154
  • 1
    *"I do the following"* Is this exactly the HTML source you have? The code doesn't seem to be inside ` – Felix Kling Feb 03 '14 at 01:10
  • Sorry. I just left it out in the question. You can assume syntax is fine. – Maximus S Feb 03 '14 at 01:12
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Barmar Feb 03 '14 at 01:14
  • Can you be a bit more precise in your questions? Where's the div? What do you mean by "I realize that I also append another div when I append the above element"? – Leo Feb 03 '14 at 01:15
  • possible duplicate of [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by-event-hand) – Felix Kling Feb 03 '14 at 01:17
  • Thanks for the links! However, I don't think those two really address this specific problem. I edited the question to be more precise. – Maximus S Feb 03 '14 at 01:25

1 Answers1

0

The problem is with your linkEl. The variable is the string, not the DOM element.

When you run $('body').append(linkEl); jQuery converts the string into DOM elements, but you haven't updated your reference.

Try something like

var linkEl = '<a href="#">foo</a>';

// Reassign the variable to the DOM element created by jQuery.
linkEl = $('body').append(linkEl);

linkEl.click(function () {
  alert('hello');
});

Here's an updated example.

reergymerej
  • 2,371
  • 2
  • 26
  • 32