If I run the following code I get, as expected, 1, because the a element is inside the div element.
HTML:
<div class=".holder">
<a href="#" class=".link">a</a>
</div>
jQuery:
$(document).click(function (e) {
alert($(e.target).closest(".holder").length);
});
Now, the inside a element needs to repopulate the div element, including the a element itself, so:
$(".link").on("click", function (e) {
e.preventDefault();
$(".holder").html("some html");
});
The problem is: because the document click occurs after the a element click (makes sense, hierarchy), if I click the a element, I get 0 instead of 1, because the a element parent doesn’t exist anymore, and the a element itself only exists in memory.
Is there a way to solve this without check for the a element click itself?
You could defer the HTML replacement: