选择最近的标题元素 [英] Selecting nearest heading element

查看:46
本文介绍了选择最近的标题元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于给定的元素(可能嵌套在DOM中),我试图在上面的DOM中选择它的最近"(最近)标题元素<h1>-<h6>.由于标题不是祖先,因此jQuery的closest将无法满足要求.

For a given element (which may be nested down in the DOM), I am trying to select it's 'closest' (nearest) heading element <h1>-<h6> in the DOM above. As the heading is not an ancestor, jQuery's closest will not suffice.

为澄清起见,该元素不太可能是标题的同级元素-例如下面代码的<span>.

To clarify, the element is not likely to be a sibling of the headings - e.g. the <span>s of the code below.

示例HTML:

<section>
    <h1>Heading<h1>
    <h2>Subheading</h2>
    <p>Lorem ipsum...</p>
    <ul>
      <li>
          <p> ... <span class="where-am-i">What heading am I under?</span> ... </p>
      </li>
    </p>
    <!-- Should return the H2 above -->
    <p>Lorem ipsum... </p>
</section>

这个问题类似,但又有足够的差异(我希望如此).

Similar, but different enough (I hope), to this question.

推荐答案

我有此解决方案,但它long之以鼻.有什么简单的方法可以清理我的代码?

I have this solution, but it is long-winded. Is there anything easier that will clean up my code?

target = $(element)
    .parentsUntil("*:has('h1, h2, h3, h4, h5, h6')")  // element's ancestors until one which has children headings 
    .last()  // the ancestor that has sibling headings
    .prevUntil('h1, h2, h3, h4, h5, h6')   // previous siblings until the nearest heading
    .andSelf()  // in case the prevUntil() returns nothing
    .first()    // the first element after the heading
    .prev();    // the heading!

这是我的 Plnkr .

这篇关于选择最近的标题元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆