Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if the clicked element is a child of some ID?

Tags:

jquery

How can I determine whether this clicked element is a subset of somemenu ?

jQuery Example:

var clicked = e.target;

// this checks see if the clicked has id of somemenu.
$(clicked).attr("id") == '#somemenu';

HTML example of somemenu:

<div id="somemenu">
   <a href="something.php"> menu 1 </a>
   <!--bunch of other elements here, can be anything.-->
</div>

I want to catch any element that is subset of `div#somemenu? when it's clicked.

like image 784
KJW Avatar asked Sep 25 '10 01:09

KJW


2 Answers

This will work:

if ($(clicked).parents('#somemenu').length) {
    // I am a child of somemenu so do stuff.
}    
like image 133
Stephen Avatar answered Sep 23 '22 05:09

Stephen


it's more easy work with stopPropagation and the method on of jquery:

jQuery('#myID').on('click',"*",function(e){
          e.stopPropagation(); //stop the propagation          
          console.log("Clicked element: ",jQuery(this)); //get the element clicked by the mouse
          console.log("Parent: ",jQuery(this).closest("#myID"));

});

if you don't stop the propagation you should call to all parents of the jQuery(this);

like image 44
Robert Blasco Villarroya Avatar answered Sep 22 '22 05:09

Robert Blasco Villarroya