Lyze
Lyze

Reputation: 75

How to select subchildren starting with a specific one via XPath

I have the following HTML tree (Note that the id is "msg-uniqueRandomNumber"):

<div class="elements">
    <div class="grp" id="msg-128736"> </div>
    <div class="grp" id="msg-312422"> </div>
    <div class="grp" id="msg-012312"> </div>
    <div class="grp" id="msg-567243"> </div>
</div>

I want to match a group of elements where the first one is a specific id.

Example: Match every class grp starting with msg-012312.

Result should be:

    <div class="grp" id="msg-012312"> </div>
    <div class="grp" id="msg-567243"> </div>

Upvotes: 1

Views: 62

Answers (2)

kjhughes
kjhughes

Reputation: 111491

Choroba's nice explanation and fine answer are correct (+1), but here's a simpler XPath that will work:

//div[@class="grp" and not(./following-sibling::div[@id="msg-012312"])]

Read as

Select all of the grp div elements that do not appear before the div with an id of msg-012312.

Upvotes: 2

choroba
choroba

Reputation: 241738

To select a div of the given class and id, use

//div[@class="grp" and @id="msg-012312"]

To select the following siblings, you can use

following-sibling::div[@class="grp"]

Putting both nodesets together with the union operator |:

( //div[@class="grp" and @id="msg-012312"]
| //div[@class="grp" and @id="msg-012312"]/following-sibling::div[@class="grp"] )

Upvotes: 1

Related Questions