在jQuery中获取元素的任意级父元素(带有类选择器)

时间:2017-07-11 08:23:10

标签: jquery

在jQuery中,如何使用特定的选择器获取元素的任意级父元素?我不确切知道它在哪里,我只知道它存在于当前元素上方的DOM中。这是我想要的一个原始例子:

<div id="world" >
   <div class="forest" id="some_random_forest">
       <div id="groove">
          <div id="oak_tree">
             <div id="a_branch"></div>
          </div>
       </div>
   </div>

   <div id="south_america">
      <div class="forest" id="rain_forest">
         <div id="jungle_tree"></div>
      </div>
   </div>

   <div id="europe">
      <div id="germany">
         <div class="forest" id="black_forest">
             <div id="pine_tree">
                <div id="a_pine_needle"></div>
                <div id="cute_squirrel"></div>
             </div>
         </div>
      </div>
   </div>
</div>

<script type="application/javascript">
   function getParentForest(subject){
      // return the closest div with the class forest to the subject element.
   }

   // So this would be the return values of the following function calls
    getParentForest("#a_branch");   // returns $("#some_random_forest")
    getParentForest("#jungle_tree");   // returns $("#rain_forest")
    getParentForest("#a_pine_needle");   // returns $("#black_forest")
    getParentForest("#cute_squirrel");   // returns $("#black_forest")
</script>

1 个答案:

答案 0 :(得分:1)

你正在寻找这个:

$('#a_branch').closest('.forest');