Sidharth
Sidharth

Reputation: 27

How to select the div tag with the value of text node of label tag

<abc>
  <div>
    <input>
    <label>A
      <span>C</span>
    </label>
  </div>
  <div>
    <input>
    <label>AB
      <span>D</span>
    </label>
  </div>
</abc>

I need to select the <div> tag with search criteria of text in the <label> tag. Text inside <span> is dynamic and sometimes it is empty, so this should not be used as search criteria.

What I have so far tried is below, both could not return the answer:

//div[./label[.='A']]

//div[./label[text().='A']]

Upvotes: 0

Views: 548

Answers (3)

E.Wiest
E.Wiest

Reputation: 5915

One way to do it with ancestor (first will select div with label "A", second will select div with label "AB") :

//label[./text()[normalize-space()="A"]]/ancestor::div
//label[./text()[normalize-space()="AB"]]/ancestor::div

With contains function :

//label[contains(./text(),"A") and string-length(normalize-space(./text()))=1]/ancestor::div
//label[contains(./text(),"AB")]/ancestor::div

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193338

To select the parent <div> element with respect to it's child <label> element's text using Selenium you can use the following based Locator Strategies:

  • Selecting <div> with child <label> text as AB

    //div[//label[contains(., 'AB')]]
    

Note: still doesn't supports so you have to use

Upvotes: 1

frianH
frianH

Reputation: 7563

Use parent:

//label[text()='A']//parent::div

Also you can use text contains:

//label[contains(text(),'A')]//parent::div

Upvotes: 0

Related Questions