0

Given html:

<div class="class1">
    <div class="class2">1 2 3</div>
    <div class="class3">a b c</div>
</div>

As i have several div elements in my html which uses the class "class1" and none has a id i want to find/fetch this parent element by the text of its children.

I tried different variants like

By.xpath("//div[contains(@class, 'class1') " 
    + "and text()[contains(.,'1 2 3')] "
    + "and text()[contains(.,'a b c')]]"));

but nothing seems to work yet.

In the example above i guess the text of the class1 element is checked but not of its children.

Can anybody help?

StephanM
  • 1,350
  • 2
  • 24
  • 50

2 Answers2

1

So you're looking for a div with class class1 that has children with texts 1 2 3 and a b c. From your example of what you've tried, I'm assuming there are no further conditions (eg class) on the children:

//div[@class='class1' and div/text()='1 2 3' and div/text()='a b c']

You can make those children node names into * if you don't care whether they are divs or not. You can make the children node names prefixed by descendant:: if you don't require them to be direct children.

AakashM
  • 62,551
  • 17
  • 151
  • 186
1

Try any of these below mentioned xpath.

Using class attribute of <div> tag.

//div[@class='class2']/..//div[@class='class3']/..//parent::div[@class='class1']

Explanation of xpath: First locate both child elements using the class attribute of <div> tag and then move ahead with parent keyword with <div> tag along with class attribute.

OR

Using text method along with <div> tag.

//div[text()= '1 2 3']/..//div[text()= 'a b c']/..//parent::div[@class='class1']

Explanation of xpath: First locate both child elements using the text method of <div> tag and then move ahead with parent keyword with <div> tag along with class attribute.

These above xpath will locate your parent element <div class="class1">

Jainish Kapadia
  • 2,603
  • 5
  • 18
  • 29