Search code examples
javascriptjqueryajaxdeveloper-tools

Document ready not hit on page load, but it works using Developer Tools Console


On Ajax Success, li element is appended to ul.

$.ajax({
           ..
     success: function (response) {
         response.data.forEach(function (x) {
            $("#ulMain").append('<li class="liSub">' + x + '</li>');
     }
});

It creates sth like this:

<ul>
  <li class="liSub">ABC</li>
  <li class="liSub">BCF</li>
</ul>

I want the dynamically added li elements to fire an alertbox on click. But the code below is not being hit.

$(document).ready(function () {
    $(".liSub").on("click", function () {
        alert("Fired");
    });
});

Interestingly, If I run the document.ready section of the code using F12 - Console, it works. What stops it run normally, and lets it run through console?


Solution

  • You missed . prefix for class and use event delgation for created dynamic dom elements

    $("ul").on("click", '.liSub', function () {
         alert("Fired");
    });