You can use the preceding-sibling
and following-sibling
selectors in XPath to do this!
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