Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery event.target is_a_child_of(element)

Given element, a variable containing a javascript object/DOM element, how do I determine if the event.target is an element inside element or not?

function(event){
   // assume that var element exists in this scope
   if(event.target == a_child_of(element))
      // do something
}


<div id="myDiv">
   <div class="innerDiv">
      <input type="text"/>
   </div>
</div>

If element is myDiv, an event occurring on the inner div or the input, or any other element that may exist inside myDiv should cause the statement to evaluate to true.

I imagine that I could use a recursive function to build an array of child elements and then check if the event.target is in the array, but I want to see if there's a simpler answer first.

like image 720
Nick Avatar asked Aug 31 '12 20:08

Nick


People also ask

What is jQuery event target?

The event. target property returns which DOM element triggered the event. It is often useful to compare event. target to this in order to determine if the event is being handled due to event bubbling.

How do I find my target class name for an event?

You can use jQuery to check for classes by name: $(event. target). hasClass('konbo');

Is event target deprecated?

Obsolete This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time.


2 Answers

You can also use .has()

if ($(element).has(e.target).length > 0){
//
}
like image 97
Musa Avatar answered Sep 21 '22 18:09

Musa


jQuery to the rescue:

if (jQuery.contains(element, e.target))
like image 29
SLaks Avatar answered Sep 18 '22 18:09

SLaks