Prototype-element-descendantof

提供:Dev Guides
移動先:案内検索

プロトタイプ-descendantOf()メソッド

このメソッドは、要素が祖先の子孫であるかどうかを確認します。

Element.descendantOfは内部的に祖先に$()を適用するため、2番目の引数として要素または要素のidを無差別に受け入れます。

構文

element.descendantOf(ancestor);

戻り値

要素が祖先の子孫であることがわかると、trueを返します。そうでない場合はfalseを返します。

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>

      <script>
         function isDescendant() {
            var father = $('father');
            var kid = $('kid');

           //This is correct relationship and will be printed
            if( kid.descendantOf(father) ) {
               alert( "Kid is descendant of father" );
            }

           //This is wrong relationship and will not be printed
            if( father.descendantOf(kid) ) {
               alert( "Father is descendant of kid" );
            }
         }
      </script>
   </head>

   <body>
      <p>Click isDescendant button to see the result.</p>
      <div id = "grandfather">
         <div id = "father">
            <div id = "kid"></div>
         </div>
      </div>
      <br/>

      <input type = "button" value = "isDescendant" onclick = "isDescendant();"/>
   </body>
</html>

出力