r-kane
r-kane

Reputation: 39

Select child of element if exists, else take parent

I want to catch the error message text from within a <span> tag, or if it does not exist, from its parent, a div tag. For this I need a valid xpath expression that can handle both cases as one if possible.

Here is the html code. It's either version 1:

<div class='error-message'>
  some error message
</div>

or version 2:

<div class='error-message'>
  <span>
    some other error message
  </span>
</div>

So the xpaths would be:

v1: //div[@class='error-message']

v2: //div[@class='error-message']/span

Now I need to combine (with some 'or' expression maybe?) v1 and v2 somehow.

If have tried:

I also tried, what was given in this answer: XPath select child if child exists, else select parent but using the code .../(span, .[not(span)]) seems to be invalid, at least in Ranorex.

Upvotes: 2

Views: 1135

Answers (2)

Manish
Manish

Reputation: 514

Since, you do not know if the error message is going to be present in the div tag or span tag, you can try the below approach

.//unknown[@innertext~'error message']

Additionally, it will work if the object has been identified correctly up untill the div tag in the original post.

Upvotes: 0

phibao37
phibao37

Reputation: 2350

You could try following approach:

//div[@class='error-message']/descendant-or-self::*[@innertext!='']

Note: there is a limitation that if the text content is empty, it will not work :(

Upvotes: 0

Related Questions