Pregunta

I'm using the Moovweb SDK to transform a website, and I have a lot of pages with content that matches this format. There is an <h2> that begins a section, and that section has a random number of <p> elements.

Since these elements have no attributes, I can’t select by class or id. I want to select the first and last <p> in each section. 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>?

<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>
¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top