Search code examples
javascriptjqueryonclickchildren

on() jQuery not working on children of a div


HTML code:

<input type="text" name="subcat" class="subcat input1"/>
<div class="input dispsubcat" id="dispsubcat">
    <div class="sub"> abc</div>
    <div class="sub"> xyz</div>
</div

jQuery code:

$(".input").children("div").on("click",function(){  //does not work
    console.log("hello"); 
})

$(".sub").on("click",function(){ //also does not work
    console.log("hi");
})

The following code works which is not what I want:

$(".input").on("click",function(){ console.log("ab");})

Solution

  • Assuming those div elements are added dynamically, you'll need to delegate the click event to your div elements by passing in your "div" selector as the second argument within jQuery's on() method:

    $(".input").on("click", "div", function() {
        ...
    });
    

    From jQuery's on() documentation:

    When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.