Dmitriy Zhernoviy
Dmitriy Zhernoviy

Reputation: 111

Get Checkbox label text Selenium C#

I'm trying to get the text value of checkbox label. Here is an HTML code

<div id="content" class="large-12 columns">
        <div class="example">
  <h3>Checkboxes</h3>
  <form id='checkboxes'>
    <input type="checkbox"> checkbox 1</br>
    <input type="checkbox" checked> checkbox 2
  </form>
</div>

So What I have tried so far

  1. Driver.FindElement(By.XPath("//input[@type='checkbox']")).Text;
  2. Driver.FindElement(By.XPath("//input[@type='checkbox']")).GetAttribute("value");
  3. Driver.FindElement(By.XPath("//input[@type='checkbox']")).GetAttribute("name");
  4. Driver.FindElement(By.XPath("//input[@type='checkbox']")).GetAttribute("innerText");
  5. Driver.FindElement(By.XPath("//input[@type='checkbox']")).GetAttribute("innerHTML");

Here is a screenshot

All this attempts return "". Any ideas how to get it or Javascript is my only option ?

Upvotes: 1

Views: 2041

Answers (4)

Neeraj vishwakarma
Neeraj vishwakarma

Reputation: 117

You can also use CSS Selector to get the checkbox label:

Element CheckBox = Driver.FindElement(By.CssSelector("input[type='checkbox']"));

string firstChkBoxTxt = CheckBox.FirstOrDefault().GetAttribute("innerText");
string secondChkBoxTxt = CheckBox.LastOrDefault().GetAttribute("innerText");

Upvotes: 0

Mahipal
Mahipal

Reputation: 910

You can try following to get the required text from the two checkboxes:

Driver.FindElement(By.XPath("//form[@id='checkboxes']/input[@type='checkbox'][1]")).Text
Driver.FindElement(By.XPath("//form[@id='checkboxes']/input[@type='checkbox'][2]")).Text

Let me know, if above code does not work for you.

Upvotes: 0

Daniel Manta
Daniel Manta

Reputation: 6683

The xpath for a text following an input tag is //input[1]/following-sibling::text()[1] but there are serious limitations for Selenium to run expressions like this. It only can handle tag elements. Try to get the parent and retrieve texts from there.

string[] texts = Driver.FindElement(By.XPath("//form[@id='checkboxes']"))
   .GetAttribute("innerText")
   .Split("\r\n".ToCharArray()
);

Then texts[0] returns:

checkbox 1

Upvotes: 1

Gareth
Gareth

Reputation: 11

Add an class or id attribute to the checkboxes and then try to find the element by css selector like: Driver.FindElement(By.CssSelector(""))

Upvotes: 0

Related Questions