Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  139] [ 3]  / answers: 1 / hits: 175765  / 14 Years ago, mon, september 20, 2010, 12:00:00

I have the following code.



<html>
<head>
<script type=text/javascript src=http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js></script>
</head>

<div id=hello>Hello <div>Child-Of-Hello</div></div>
<br />
<div id=goodbye>Goodbye <div>Child-Of-Goodbye</div></div>

<script type=text/javascript>
<!--
function fun(evt) {
var target = $(evt.target);
if ($('div#hello').parents(target).length) {
alert('Your clicked element is having div#hello as parent');
}
}
$(document).bind('click', fun);
-->
</script>

</html>


I expect only when Child-Of-Hello being clicked, $('div#hello').parents(target).length will return >0.



However, it just happen whenever I click on anywhere.



Is there something wrong with my code?


More From » jquery

 Answers
4

If you are only interested in the direct parent, and not other ancestors, you can just use parent(), and give it the selector, as in target.parent('div#hello').



Example: http://jsfiddle.net/6BX9n/



function fun(evt) {
var target = $(evt.target);
if (target.parent('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}


Or if you want to check to see if there are any ancestors that match, then use .parents().



Example: http://jsfiddle.net/6BX9n/1/



function fun(evt) {
var target = $(evt.target);
if (target.parents('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}

[#95562] Friday, September 17, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
siena

Total Points: 199
Total Questions: 91
Total Answers: 91

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;