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>