0

I have been thinking a lot, Why when I use jquery the following code runs perfectly with the nested onclick event, as far as I know that nested event should be called once the "father" event was called, and as far as I know that never happens, but, incredibly for me, it works.

$(function() {
    $("#add").on("click", function() {
        var val = $("input").val();
        if(val !== '') {
            var elem = $("<li></li>").text(val);
            $(elem).append("<button class='rem'>X</button>");
            $("#mylist").append(elem);
            $("input").val("");
            $(".rem").on("click", function() {
                $(this).parent().remove();
            });
        }
    });
});

but when I unnest the "on('click'" the browser doesn't recognize that event :(, like the following example. Can someone explain me the reason for that, am I missing something?

$(function() {
    $("#add").on("click", function() {
        var val = $("input").val();
        if(val !== '') {
            var elem = $("<li></li>").text(val);
            $(elem).append("<button class='rem'>X</button>");
            $("#mylist").append(elem);
            $("input").val("");
        }
    });
    $(".rem").on("click", function() {
        $(this).parent().remove();
    });
});
  • [Understanding Event Delegation](https://learn.jquery.com/events/event-delegation/) – charlietfl Feb 03 '22 at 00:17
  • @Ma3x `live()` has been deprecated for many years and was completely removed in v1.9 – charlietfl Feb 03 '22 at 00:21
  • @charlietfl It was actually removed after deprecation, so I edit my comment. – Ma3x Feb 03 '22 at 00:27
  • Because in the first case, there is an element that matches the selector `".rem"` (since it was just appended by the code a few lines before), in the second case such an element probably does not yet exist. – Ma3x Feb 03 '22 at 00:27
  • I wasn't sure how this works and I didn't know that JS is sequential, so the explanation to this is that the code was executed only once when the website was loaded, so, the event linked to a class\tag that doesn't exist has to be inside the other event bc when the website load js let's say tag those new ".rem" tags with that "click event". – SomeRandomGuy Feb 03 '22 at 00:43
  • That is not entirely accurate because you can also use event delegation as per the duplicate link at top of page and the *"Understanding"* link I provided in the comment above – charlietfl Feb 03 '22 at 01:11

0 Answers0