alejoss alejoss - 3 months ago 8
jQuery Question

Jquery get clicked element on delegated event

I've seen similar questions but they don't resolve this problem. I have an html that looks like this:

<div id="products" class="container-fluid">
<div class="selected_product_div panel panel-default">
<div class="panel-body">
<a style="{cursor: pointer;}" class = "delete_product pull-right"><i class="fa fa-close"></i></a>
</div>
</div>
</div>
</div>


So, after the delegated event triggers, I'd like to get the
<a class="delete_product"></a>
element. But
$(this)
means the parent
<div id="products>
element.

$("#products").on("click",".delete_product", function(){
console.log($(this).hasClass(".delete_product"));
}


Of course, the console logs false. How can I get the clicked element?

$(this).find(".delete_product")
is not an option since there are many elements with the
delete_product
class.

Answer

Try this :

$(document).ready(function(){

    $("#products").on("click",".delete_product", function(){  

        alert($(this).hasClass("delete_product"));

    })

})

Final code :

<html>
    <title>This is test</title>
    <head>
        <style>   
        </style>
    </head>
    <body>
        
       <div id="products" class="container-fluid">
           
            <div class="selected_product_div panel panel-default">
                
                  <div class="panel-body">
                      <a  class = "delete_product pull-right" href="#"><i class="fa fa-close">Click Me!</i></a>                  
                  </div>
                
           </div>
           
    </div>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            
        $(document).ready(function(){

            $("#products").on("click",".delete_product", function(){  

                alert($(this).hasClass("delete_product"));

            })

        })
        
        </script>
    </body>
</html>