1. ホーム
  2. javascript

[解決済み] ある要素が親の子であるかどうかをチェックする

2022-08-12 15:59:21

質問

次のようなコードがあります。

<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>

のときだけだと思います。 Child-Of-Hello がクリックされたときだけです。 $('div#hello').parents(target).length は、>0 を返します。

しかし、どこをクリックしても起こるだけです。

私のコードに何か問題があるのでしょうか?

どのように解決するのですか?

もし、直系の親にのみ興味があり、他の先祖には興味がないのであれば、単に parent() のように、セレクタを指定します。 target.parent('div#hello') .

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');
    }
}

また、一致する祖先があるかどうかを調べたい場合は .parents() .

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');
    }
}