简体   繁体   English

在Tritium中,如何选择上一个/下一个元素?

[英]In Tritium, how can I select the previous/next element?

I'm using the Moovweb SDK to transform a website, and I have a lot of pages with content that matches this format. 我正在使用Moovweb SDK来转换网站,并且我有很多页面的内容都与此格式匹配。 There is an <h2> that begins a section, and that section has a random number of <p> elements. 有一个<h2>从一个部分开始,该部分具有随机数量的<p>元素。

Since these elements have no attributes, I can't select by class or id. 由于这些元素没有属性,因此无法按类或ID选择。 I want to select the first and last <p> in each section. 我想在每个部分中选择第一个和最后一个<p> I don't want to have to manually select like $('./p[1]') , $('./p[4]') etc... Is there a way to select the elements before and after each <h2> ? 我不想手动选择$('./p[1]')$('./p[4]')等...是否可以选择每个元素之前和之后的元素<h2>

<div>
  <h2>This is a heading</h2>
  <p>Here is some content</p>
  <p>Meh</p>
  <p>Here's another paragraph</p>
  <p>Important sentence because it's the last one</p>
  <h2>Here's a subheading</h2>
  <p>Topic sentence</p>
  <p>Bleh bleh bleh</p>
  <p>Hurray, this fragment.</p>
  <p>May the Force be with you</p>
  <p>Moovweb rocks!</p>
  <h2>New heading</h2>
  <p>More awesome content here</p>
  <p>Why is there so much stuff?</p>
  <h2>The end</h2>
  <p>Or is it?</p>
</div>

You can use the preceding-sibling and following-sibling selectors in XPath to do this! 您可以在XPath中使用preceding-siblingfollowing-sibling选择器来做到这一点!

The code would look something like this: 代码看起来像这样:

$("./div"){
  $("./h2") {
    $("following-sibling::p[1]") { # first p after h2
      # do stuff
    }
    $("preceding-sibling::p[1]") { # first p before h2
      # do stuff
    }
  }
}

See this example I created in the Tritium Tester: http://tester.tritium.io/dc25a419ac15fad70fba6fd3d3a9b512cb8430e8 请参阅我在Tritium Tester中创建的以下示例: http : //tester.tritium.io/dc25a419ac15fad70fba6fd3d3a9b512cb8430e8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM