[英]In Tritium, how can I select the previous/next element?
我正在使用Moovweb SDK来转换网站,并且我有很多页面的内容都与此格式匹配。 有一个<h2>
从一个部分开始,该部分具有随机数量的<p>
元素。
由于这些元素没有属性,因此无法按类或ID选择。 我想在每个部分中选择第一个和最后一个<p>
。 我不想手动选择$('./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>
您可以在XPath中使用preceding-sibling
和following-sibling
选择器来做到这一点!
代码看起来像这样:
$("./div"){
$("./h2") {
$("following-sibling::p[1]") { # first p after h2
# do stuff
}
$("preceding-sibling::p[1]") { # first p before h2
# do stuff
}
}
}
请参阅我在Tritium Tester中创建的以下示例: http : //tester.tritium.io/dc25a419ac15fad70fba6fd3d3a9b512cb8430e8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.