0

I search for a way to detect if a JQuery click target has a parent with a defined id $('#contextMenu') in his DOM tree.

$("html").click(function(e) {
  if ($(e.target).parents('#contextMenu')) {
    alert('yes');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="contextMenu">
  <li><a href="#"><i class="fa fa-user-plus"></i> share</a>
  </li>
</ul>

How to do that?

Satpal
  • 132,252
  • 13
  • 159
  • 168
fteinz
  • 1,085
  • 5
  • 15
  • 30
  • Check the `length` property. `if($(e.target).parents('#contextMenu').length)`. However `closest()` will be better performance wise – Satpal Dec 05 '16 at 10:26
  • Possible duplicate of [Is there an "exists" function for jQuery?](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – freedomn-m Dec 05 '16 at 10:29
  • You'd have better to delegate event, i'm guessing.. `$(document).on('click', '#contextMenu', function(){ alert('yes'); });` – A. Wolff Dec 05 '16 at 10:43

2 Answers2

3

Check the length property.

$( "html" ).click(function(e) {         
   if ($(e.target).parents('#contextMenu').length) {
      alert('yes');
   }
});

However .closest() will be better performance wise.

Thanks to @A. Wolff, You can use Event Delegation

$(document).on('click', '#contextMenu', function(){ 
   alert('yes'); 
});
Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • 1
    `closest` will be better only when the element has the given parent.. in which case even parents will work the same right? if closest is not found then its anyways bubbled up till the top right? – Rajshekar Reddy Dec 05 '16 at 10:32
  • @Reddy, `closest` will stop when matching element is found where as `parents` will continue reading to top – Satpal Dec 05 '16 at 10:33
  • @Satpal Ya but `closest()` includes element itself. So here it could give unexpected result – A. Wolff Dec 05 '16 at 10:41
  • 1
    @Satpal EDIT: i don't think it does really matter but keep comment for prosperity... ;) – A. Wolff Dec 05 '16 at 10:46
2

use the .length property to check if the element exist or not.

$( "html" ).click(function(e) {         
   if ($(e.target).parents('#contextMenu').length) {
      alert('yes');
   }
});

if length is 0 it means no elements found,

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59