Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath of first ancestor with specific class

Tags:

html

xml

xpath

enter image description here

I have the HTML in the screenshot, I can get the node with text in it using:

//div[contains(., 'Property Land')]

but now I want to go up one level and then find the table child of the first ancestor.

I tried:

//div[contains(., 'Property Land')]::div.panel

but this is failing. How to I get immediate ancestor of the text containing node?

like image 697
user1592380 Avatar asked Dec 02 '25 09:12

user1592380


1 Answers

Parent and ancestors

First, let's address the question implied by your title and assumed solution.

  • The parent abbreviation, .., can find an element's parent.

  • The ancestor:: axis can be used to select among an element's ancestors.

  • The first ancestor with a specific class of //div[contains(., 'Property Land')] can be selected by

    //div[contains(., 'Property Land')]/ancestor::div[@class="panel panel-primary"][1]
    

String values and contains()

Second, realize that your XPath,

//div[contains(., 'Property Land')]

actually already selects not only the div that immediately contains the substring, "Property Land", but also all ancestor div elements because their string values necessarily also contain the substring, "Property Land".

Therefore, you only need add a predicate to differentiate among all the div that contain the "Property Land" substring. You say you'd like the one with a panel class. Here again, be careful to realize that contains() tests for substring – both "panel panel-primary" and "panel-heading" contain the "panel" substring. Let's suppose that it's "panel" specifically that you want.

Then, use this XPath:

//div[contains(., 'Property Land')]
     [contains(concat(' ',@class,' '), ' panel ')]

to avoid matching other div elements with class attribute values that contain other "panel" substring.

See also

  • How to use XPath contains() for specific text?
  • XPath to match @class value and element value?
like image 97
kjhughes Avatar answered Dec 03 '25 23:12

kjhughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!