5
votes

I have a HTML structure that I am attempting to test using XPATH. The structure I'll looking at currently is something like:

<div id="item_1" class="item-wrapper">
    <div class="container item">

        <div class="container-header">
            <h2 id="title">test-title</h2>
            <h5 id="description">test-description</h5>
        </div>

    </div>
</div>

There are a number of 'items' in my document, each with a unique ID. Using XPATH I want to 'get' the item_1 node from the value of the title id node ("test-title" in this case).

I also want to do this in such a way that is not dependant on the node tag (div/h2/etc).

I've been playing around with predicates, but I can't seem to get a solution that works. For example:

//*[@class="item-wrapper"][./*[@id="title"][text()="test-title"]] 

Thanks for any help!

1

1 Answers

8
votes

You can use the below XPATH :

 //*[@id="title"]/ancestor::*[@id="item_1"][1]

Or, you can also use the function Function: node-set id(object)

 id('title')//ancestor::*[@id="item_1"][1]

Update

 //*[.="test-title"]/ancestor::*[@class="item-wrapper"][1]

output

<div id="item_1" class="item-wrapper">
    <div class="container item">

        <div class="container-header">
            <h2 id="title">test-title</h2>
            <h5 id="description">test-description</h5>
        </div>

    </div>
</div>