Reputation: 2199
I bind a click event over the document
. I have a div with id parent
. Now whenever the click event occur over the document
than i am trying to check the target element is the child of div ( id = parent )
or not.
<div id="parent">
<div id="c1">
<div id="gc1">
</div>
<div id="gc2">
</div>
...
</div>
...
</div>
For this purpose i wrote the following jquery code :
$(document).click( function(e) {
if($(e.target).parents("#parent").length > 0) //this condition is not
working as expected
{ }
});
What i am doing wrong here?
Upvotes: 0
Views: 80
Reputation: 17666
You could use jQuery.contains()
if( $.contains( document.getElementById('parent'), e.target) ) {
}
This will check if the target is contained within the parent container.
From the docs:
Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.
This is the reason for the getElementById..
Upvotes: 1
Reputation: 4783
EDIT Use closest... Working FIDDLE
First...this may not completely answer your question but you need the (e) in the click function.
$(document).click( function(e) {
if($(e.target).closest("#parent").length > 0)
{ }
});
Upvotes: 0
Reputation: 339816
If the code you posted is verbatim, you forgot to declare e
as a parameter to the callback function.
Apart from that, your code looks like it should work fine. However, for efficiency you could use .closest()
rather than .parents()
since that'll only return 0 or 1 elements, and not the entire chain of elements.
Upvotes: 1