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!
Hey Hemant, we can use the double dot (“..”) to access the parent of any node using the XPath. For example – The locator //span[@id=”first”]/.. will return the parent of the span element matching id value as 'first.
Xpath Descendant is defined as a context node that is represented by the descendant axis; a descendant is a child node, a child of a child, and so on; consequently, the descendant axis doesn't contain attribute or namespace nodes. XPath is a mini-language that describes a node pattern to select a set of nodes.
The descendant axis indicates all of the children of the context node, and all of their children, and so forth. Attribute and namespace nodes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With