首页 > 解决方案 > 使用 JQuery 的 find 方法,我如何根据“foo”的子元素的内容选择某个 HTML 元素“foo”的兄弟?

问题描述

假设我有如下 HTML:

<div class="foo-container">
  <div class="foo">
    <div class="foo-child">
      <span>The Important Label</span>
    </div>
  </div>
  <div class="elem-to-manipulate">
    <p>I want to manipulate the style in this because it's the sibling of "The Important Label"</p>
  </div>
</div>

p基于它的兄弟有 text 的事实,我如何定位该元素The Important Label

我遇到了类似的事情

$('.root').find('.foo > .foo-child > span:contains("The Important Label")')

这成功地让我得到了span元素。但是现在我如何获得p兄弟中的元素div?有没有办法告诉找到哪个父母得到兄弟姐妹?

标签: jqueryhtmljquery-selectors

解决方案


$('.root').find('.foo:has(> .foo-child > span:contains("The Important Label")) + div > p')
  • aaa:has(bbb)检查是否有任何匹配aaa bbb,然后才匹配aaa
  • +匹配先前匹配元素的以下兄弟

(根据您的用例,您可能对.foo:contains("The Important Label") + div > p...感到满意)


推荐阅读