Debopam
Debopam

Reputation: 3356

Selenium Java select div based on nested element text

I have below HTML structure. Would like to select the label which has

with value 3.x

I have tried below xpath expressions

"//label[contains(@class='options')]/div/p[contains(text(),'3.x')]"
"//div[@class='answerOpts']/label[contains(@class='options')]/div/p[contains(text(),'3.x')]"

But it didn't work. Received Exception org.openqa.selenium.NoSuchElementException: Unable to locate element:. Could you please let me know the solution?

HTML structure

<div class="answerOpts">
   <input class="optionRadios" type="radio" name="2565" id="answer_9218" value="9218">
   <label class="options searchable" for="answer_9218">
      <div>
         <p>2.x</p>
      </div>
   </label>
   <input class="optionRadios" type="radio" name="2565" id="answer_9219" value="9219">
   <label class="options searchable" for="answer_9219">
      <div>
         <p>3.x</p>
      </div>
   </label>
   <input class="optionRadios" type="radio" name="2565" id="answer_9220" value="9220">
   <label class="options searchable" for="answer_9220">
      <div>
         <p>4.x</p>
      </div>
   </label>
   <input class="optionRadios" type="radio" name="2565" id="answer_9217" value="9217">
   <label class="options searchable" for="answer_9217">
      <div>
         <p>1.x</p>
      </div>
   </label>
</div>

Upvotes: 0

Views: 171

Answers (2)

Sers
Sers

Reputation: 12255

Here some xpath examples how you can get label element:

//label[normalize-space(.)='3.x']
//label[contains(@class,'options') and .//p[.='3.x']]
//label[contains(@class,'options') and @for and .//p[.='3.x']]
//p[.='3.x']/ancestor::label[1]
//p[.='3.x']/ancestor::label[contains(@class,'searchable')][1]

Upvotes: 1

jitendra gupta
jitendra gupta

Reputation: 47

try with below xpath

.//div/p[text()='3.x']/parent::div/parent::label/preceding-sibling::input[1]

Upvotes: 1

Related Questions