• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • parentsUntil()

    查找当前元素的所有的前辈元素,直到遇到选择器, DOM 节点或 jQuery 对象匹配的元素为止,但不包括这些元素。

    .parentsUntil([selector ][, filter ])
    • selector类型: Selector。选择器字符串,用于确定匹配到哪个祖先元素时停止匹配。
    • filter类型: Selector。一个字符串,用于匹配元素的选择器表达式字符串。
    .parentsUntil([element ][, filter ])
    • element类型: Element or jQueryDOM节点或jQuery对象,用于确定到哪个前辈元素时停止匹配。
    • filter类型: Selector。一个字符串,用于匹配元素的选择器表达式字符串。

    如果提供一个jQuery对象代表DOM元素集合,.parentsUntil()方法会找遍所有这些元素的前辈元素,直到遇到了跟参数匹配的元素才会停止。返回的jQuery对象中包含了所有找到的前辈元素,除了与.parentsUntil()选择器匹配的那个元素。

    如果提供的选择器没有匹配到任何元素,或者没有提供选择器,那么所有的祖先元素都会被选中。其效果与没有提供参数的.parents()方法是一样的

    从 jQuery 1.6 开始,一个DOM节点或jQuery对象,而不是一个选择器,也可以作为.parentsUntil()第一参数.

    该方法选择性地接受一个选择器表达式作为它的第二个参数。如果此参数提供,元素将通过测试它们是否匹配而被过滤的。

    例子

    Find the ancestors of <li class="item-a"> up to <ul class="level-1"> and give them a red background color. Also, find ancestors of <li class="item-2"> that have a class of "yes" up to <ul class="level-1"> and give them a green border.

    <!DOCTYPE html>
    <html>
    <head>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
     
    <ul class="level-1 yes">
      <li class="item-i">I</li>
      <li class="item-ii">II
        <ul class="level-2 yes">
          <li class="item-a">A</li>
          <li class="item-b">B
            <ul class="level-3">
              <li class="item-1">1</li>
              <li class="item-2">2</li>
              <li class="item-3">3</li>
            </ul>
          </li>
          <li class="item-c">C</li>
        </ul>
      </li>
      <li class="item-iii">III</li>
    </ul>
    <script>
    $("li.item-a").parentsUntil(".level-1")
      .css("background-color", "red");
     
    $("li.item-2").parentsUntil( $("ul.level-1"), ".yes" )
      .css("border", "3px solid green");
     
    </script>
     
    </body>
    </html>
    
    • I
    • II
      • A
      • B
        • 1
        • 2
        • 3
      • C
    • III

    上篇:parents()

    下篇:closest()