3

I have a div that contains several, but a varying amount of h3s (as well as a lot of p but they can be ignored). The last h3 has a constat value (but no class or id). There is also an img with some, probably unique, properties a the end of the div. All in all it looks something like this:

    <div class="article__body">
        <p>value</p>
        <h3>changing value</h3>
        <p>value</p>
        <p>value</p>
        <h3>changing value</h3>
        <h3>changing value</h3>
        *and so on for a bit*
        <h3>THIS IS THE VALUE I AM INTEREST IN</h3>
        <h3>THIS VALUE IS CONTSTANT</h3>
       <img srcset="/siteassets/lobby.png?preset=340&amp;version=63684897580 340w">
    </div>
   </div>
   <aside class="service">

Can I go to either to the h3 with the constant value, the img or maybe the aside tag outside this div (and one more level of divs) and then step back to the h3 I am interested in?

4 Answers 4

2

This expression is simpler and also seems to work:

//h3[contains(text(),'CON')]/preceding-sibling::h3[1]
Sign up to request clarification or add additional context in comments.

Comments

2

Note that your subject question "access penultimate node of a list with variable length?" in XPath would simply translate into //div[@class = 'article__body']/h3[last() - 1], i.e. in the list of h3 children you can select the penultimate with h3[last() - 1]: https://xqueryfiddle.liberty-development.net/3Nqn5Yi

Comments

1

You can use easily find h3 with a constant value. Use preceding-sibling xpath axis to get its predecessor.

How to get the preceding element?

preceding would also work in your case Which should I use: preceding:: or preceding-sibling::?

Comments

1

Try Following Xpath.

To access h3 tag with constant value

'//div[@class="article__body"]/h3[text()="THIS VALUE IS CONTSTANT"]'

OR

'//div[@class="article__body"]/h3[contains(.,"CONTSTANT")]'

To get last h3 node of a tree.

'(//div[@class="article__body"]/h3)[last()]'

To access image with srcset property.

'//div[@class="article__body"]/img[contains(@srcset,"/siteassets/lobby.png?preset")]'

EDITED

'(//div[@class="article__body"]/h3)[last()-1]'

OR

'//div[@class="article__body"]/h3[text()="THIS VALUE IS CONTSTANT"]/preceding-sibling::h3[1]'

2 Comments

Yes, but how do I get the previous h3 from the constant h3 or last h3?
@d-b : Please check 2 options i have provided in edited sections.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.