Search code examples
javascripthtmljqueryjquery-eventsevent-delegation

Bind click event for parent using child element's id


I want to bind a click event on parent element using child element's id.

I have this:

<span class='k-link'> 
   <div id='myDiv'> </div>
</span>

<span class='k-link'> 
   <div id='myDiv2'> </div>
</span>

I want to do this:

$("#myDiv:parent").click(function() { });   //Does not work as expected
$("#myDiv2:parent").click(function() { });   //Does not work as expected

However, this does not result in the desired behavior, and the click event only works when clicked on myDiv and not on span. I have no control over span, I can only give id to the div, how can I bind a click event for the myDiv's parent (which is a span tag).

Is this possible?


Solution

  • Use parent() method like following.

    $("#myDiv").parent().click(function() {
        alert('OK');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span class='k-link'> 
       <div id='myDiv'>DIV</div>
    </span>