2

I have the following HTML and and XPath working

<div class="panel panel-default">
    <div class="panel-heading"><h1>Text to find</h1></div>
    <div class="panel-body">
        <div>
            ...
        </div>
    </div>
</div>

XPath:

.//div[div[@class[contains(.,'panel-heading')]][.//*[text()='Text to find']]]

The XPath expression will select the outer <div>.

Now if I remove the <h1> tag the XPath expression will no longer find the outer div. Can anyone explain me why, and what to do instead if I want to get the same result in the two cases.

0

1 Answer 1

3

That's because .//* part returns descendant elements of the <div class="panel-heading">. When you remove the h1 tag, the text node 'Text to find' is no longer contained in any descendant element (it is direct child of the context element now), hence can't be found using expression .//*[text()='Text to find'].

To make it work with and without h1 element, you can alter the predicate expression mentioned above to .//text()[.='Text to find'] :

.//div[div[@class[contains(.,'panel-heading')]][.//text()[.='Text to find']]]

.//text() simply returns descendant text nodes from current context element.

Sign up to request clarification or add additional context in comments.

1 Comment

Kudos for the fast response :)

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.